Next greater number set digits

PROBLEM :

Given a number n, find the smallest number that has same set of digits as n and is greater than n. If x is the greatest possible number with its set of digits, then print “not possible”.

Input:

The first line of input contains an integer T denoting the number of test cases.
The first line of each test case is n,n is the number.

Output:

Print the greater number than n with same set of digits and if not possible then print "not possible" without double quote.

Constraints:

1 = T = 100
1 = n = 100000

Example:

Input
2
143
431

Output
314
not possible

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------

#include<iostream>
using namespace std;
#include<string.h>
#include <algorithm>  // for sort() function
                 
char* Next_greater_number(char* ) ;
char* swap(char* ,int ,int ) ;

//char* sort(char* ,int ,int ) ;

int main()
 {
int t ;
char *str ;
str=(char*)malloc(100000*sizeof(char)) ;
cin>>t ;
while(t--)
{
   cin>>str ;
 
   str=Next_greater_number(str) ;
   cout<<str<<endl ;
}
return 0;
}

char* Next_greater_number(char* str)
{
    int l ;
    l=strlen(str) ;
 
    int i ;
    for(i=l-1;l>0;i--)
        if(str[i]>str[i-1])
            break ;
         
    if(i==0)
    {
    strcpy(str,"not possible") ;
    return str ;
    }
     
    int ele1,ele2 ;
    ele1=i-1 ;
    ele2=i ;
 
    for(i=i;i<l;i++)
        if(str[i]>str[ele1]&&str[i]<str[ele2])
            ele2=i ;
         
    str=swap(str,ele1,ele2) ;
 
    sort(str+ele1+1,str+l) ;       // can't use sorting algo as length of string is very large
 
    //str=sort(str,ele1,l) ;        
 
    return str ;
}

char* swap(char* str,int a,int b)
{
char temp ;

temp=str[a] ;
str[a]=str[b] ;
str[b]=temp ;

return str ;
}

/*
char* sort(char* str,int n1,int n2)
{
if(n1>=n2)
return str ;

int i,j,k ;
char temp ;
k=0 ;

for(i=n1;i<n2-1;i++)
{
for(j=n1;j<n2-k;j++)
{
if(str[j]>str[j+1])
{
temp=str[j] ;
str[j]=str[j+1] ;
str[j+1]=temp ;
k++ ;
}
}
}
return str ;
}                                              */                                

---------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )