-
Notifications
You must be signed in to change notification settings - Fork 688
/
NextHighestNumber.java
54 lines (41 loc) · 1.41 KB
/
NextHighestNumber.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package math;
public class NextHighestNumber {
/*
* Given a number, find the next higher number which has the exact same set of digits as the original number
* Input: 1234
* Output: 1243
*
* Step 1) Iterate the array from the right side, find the digit which is greater than the digit on the left side. - (a)
* Step 2) If it is zero, then we can assume that there are no permutations available
* Step 3) Iterate through the array from the left side, find the next digit after (a) which is greater than arr[(a)-1] and is less than arr[(a)]
* Step 4) Swap these values
*
* */
public static Integer findNextHighestNumber(int num) {
char[] c = String.valueOf(num).toCharArray();
int a = 0;
int length = c.length;
for (int i = length - 1; i > 0; i--) {
if (c[i] > c[i - 1]) {
a = i;
break;
}
}
if (a == 0) return num;
int number = c[a - 1];
int min = a;
for (int i = a + 1; i < length; i++) {
if (c[i] > number && c[i] < c[min]) {
min = i;
}
}
char temp = c[a - 1];
c[a - 1] = c[min];
c[min] = temp;
return Integer.valueOf(new String(c));
}
public static void main(String[] args) {
int n = 1234;
System.out.println(findNextHighestNumber(n));
}
}