Thursday, January 19, 2012

Find the next higher number with the same digits


//Code to find the next higher number with the same digits.
#include<iostream>
using namespace std;
int main()
{
long long int m,n,A[1000],i,j,k,temp,same;
cin>>n;
same=0;
i=0;
while(n>0)
{
A[i]=n%10;
n=n/10;
i++;
}
//Finding the first digit at which the next digit is less than this digit starting from the left.
for(j=0;j<i-1;j++)
{
if(A[j+1]<A[j])
{
//Finding the smallest digit greater than the pivotal digit.
for(k=0;k<=j;k++)
{
if(A[k]>A[j+1])
{
break;
}
}
//Swapping the two digits.
temp=A[k];
A[k]=A[j+1];
A[j+1]=temp;
same=1;
break;
}
}
//If the next higher number is possible with the same number of digits
if(same==1)
{
m=A[i-1];
for(k=i-2;k>j;k--)
{
m=m*10+A[k];
}
for(j=0;j<=k;j++)
{
m=m*10+A[j];
}
}
//If the next higher number needs to have greater number of digits.
else
{
m=A[0];
m=m*10+A[0];
for(j=1;j<i;j++)
{
m=m*10+A[j];
}
}
cout<<m<<endl;
fflush(stdin);
getchar();
return 0;
}
Input: 37723971
Output: 37727139