File tree Expand file tree Collapse file tree 1 file changed +10
-1
lines changed Expand file tree Collapse file tree 1 file changed +10
-1
lines changed Original file line number Diff line number Diff line change 88 * @author: ramswaroop 
99 * @date: 10/30/15 
1010 * @time: 11:01 AM 
11+  * @see: http://www.geeksforgeeks.org/find-next-greater-number-set-digits/ 
1112 */ 
1213public  class  NextLargerNumber  {
1314
@@ -30,17 +31,21 @@ public static int findNextLargerNumber(Integer n) {
3031        // construct int array containing all  
3132        // digits in number {@param n}   
3233        for  (int  i  = 0 ; i  < len ; i ++) {
33-             a [i ] = Integer .parseInt (str .charAt (i ) +  "" );
34+             a [i ] = Integer .parseInt (String . valueOf ( str .charAt (i )) );
3435        }
3536
37+         // find the index where a digit is greater than its previous  
38+         // digit (from left) 
3639        int  i  = len  - 1 ;
3740        while  (i  > 0 ) {
3841            if  (a [i ] > a [i  - 1 ]) break ;
3942            i --;
4043        }
4144
45+         // digits are already in descending order, so return 
4246        if  (i  <= 0 ) return  -1 ;
4347
48+         // find index of smallest no. greater than a[i-1]  
4449        minIndex  = i ;
4550        int  j  = len  - 1 ;
4651        while  (j  >= i ) {
@@ -50,10 +55,14 @@ public static int findNextLargerNumber(Integer n) {
5055            j --;
5156        }
5257
58+         // swap a[i-1] with the smallest no. on the right 
59+         // of i-1 index which is larger than a[i-1]  
5360        swap (a , i  - 1 , minIndex );
5461
62+         // sort all digits to the right of i-1 index 
5563        QuickSort .quickSort (a , i , len  - 1 );
5664
65+         // construct the no. from the int array 
5766        StringBuilder  builder  = new  StringBuilder ();
5867        for  (int  k  = 0 ; k  < len ; k ++) {
5968            builder .append (a [k ]);
 
 
   
 
     
   
   
          
    
    
     
    
      
     
     
    You can’t perform that action at this time.
  
 
    
  
    
      
        
     
       
      
     
   
 
    
    
  
 
  
 
     
    
0 commit comments