Smallest different

Practice

Author: Anurag
Tester: Anurag
Editorialist: Anurag

DIFFICULTY:

EASY,MEDIUM,GREEDY,STRING,CAKEWALK, SIMPLE

PREREQUISITES:

Math ,String

PROBLEM:

You are given a number N. You have to find the minimum differences between two digit of given number. NOTE-(Number(N) of digit will be greater than two)

EXPLANATION:

We have given a number in that number we have to just find out in that number smallest different between the digits

for example we have given a digit 1356

here differnt between 1 and 3 is 2
and difference between 1 and 5 is 4
difference between 1 and 6 is 5
similarly difference between 3 and 5 is 2
difference between 3 and 6 is 3
difference between 5 and 6 is 1 which is minimum hence the output will be 1

SOLUTIONS:

Setter's Solution

#include<bits/stdc++.h>
using namespace std;
void testcase()
{
long long int n,a[50];
cin>>n;

   long long int i=-1,cnt=0;
   while(n){
       a[++i]=n%10;
       n=n/10;
       cnt++;
   }
 long long  int mindiff=10,maxdiff=10;
   
   sort(a,a+cnt);
   for(int i=0;i<cnt;i++){
       maxdiff=abs(a[i]-a[i+1]);
       if(maxdiff<=mindiff){
           mindiff=maxdiff;
       }
   }
   cout<<mindiff;

}
int main()
{
int t;
cin>>t;
while(t–)
{
testcase();
cout<<endl;
}
return 0;
}

Tester's Solution

#include<bits/stdc++.h>
using namespace std;
void testcase()
{
long long int n,a[50];
cin>>n;

   long long int i=-1,cnt=0;
   while(n){
       a[++i]=n%10;
       n=n/10;
       cnt++;
   }
 long long  int mindiff=10,maxdiff=10;
   
   sort(a,a+cnt);
   for(int i=0;i<cnt;i++){
       maxdiff=abs(a[i]-a[i+1]);
       if(maxdiff<=mindiff){
           mindiff=maxdiff;
       }
   }
   cout<<mindiff;

}
int main()
{
int t;
cin>>t;
while(t–)
{
testcase();
cout<<endl;
}
return 0;
}

Editorialist's Solution

#include<bits/stdc++.h>
using namespace std;
void testcase()
{
long long int n,a[50];
cin>>n;

   long long int i=-1,cnt=0;
   while(n){
       a[++i]=n%10;
       n=n/10;
       cnt++;
   }
 long long  int mindiff=10,maxdiff=10;
   
   sort(a,a+cnt);
   for(int i=0;i<cnt;i++){
       maxdiff=abs(a[i]-a[i+1]);
       if(maxdiff<=mindiff){
           mindiff=maxdiff;
       }
   }
   cout<<mindiff;

}
int main()
{
int t;
cin>>t;
while(t–)
{
testcase();
cout<<endl;
}
return 0;
}