File tree 1 file changed +10
-1
lines changed
1 file changed +10
-1
lines changed Original file line number Diff line number Diff line change 8
8
* @author: ramswaroop
9
9
* @date: 10/30/15
10
10
* @time: 11:01 AM
11
+ * @see: http://www.geeksforgeeks.org/find-next-greater-number-set-digits/
11
12
*/
12
13
public class NextLargerNumber {
13
14
@@ -30,17 +31,21 @@ public static int findNextLargerNumber(Integer n) {
30
31
// construct int array containing all
31
32
// digits in number {@param n}
32
33
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 )) );
34
35
}
35
36
37
+ // find the index where a digit is greater than its previous
38
+ // digit (from left)
36
39
int i = len - 1 ;
37
40
while (i > 0 ) {
38
41
if (a [i ] > a [i - 1 ]) break ;
39
42
i --;
40
43
}
41
44
45
+ // digits are already in descending order, so return
42
46
if (i <= 0 ) return -1 ;
43
47
48
+ // find index of smallest no. greater than a[i-1]
44
49
minIndex = i ;
45
50
int j = len - 1 ;
46
51
while (j >= i ) {
@@ -50,10 +55,14 @@ public static int findNextLargerNumber(Integer n) {
50
55
j --;
51
56
}
52
57
58
+ // swap a[i-1] with the smallest no. on the right
59
+ // of i-1 index which is larger than a[i-1]
53
60
swap (a , i - 1 , minIndex );
54
61
62
+ // sort all digits to the right of i-1 index
55
63
QuickSort .quickSort (a , i , len - 1 );
56
64
65
+ // construct the no. from the int array
57
66
StringBuilder builder = new StringBuilder ();
58
67
for (int k = 0 ; k < len ; k ++) {
59
68
builder .append (a [k ]);
You can’t perform that action at this time.
0 commit comments