-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNextBigNumber.java
More file actions
71 lines (64 loc) · 1.32 KB
/
NextBigNumber.java
File metadata and controls
71 lines (64 loc) · 1.32 KB
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package math;
/**
* Given a number print the next big number using the same digits.
*
* Link: http://www.geeksforgeeks.org/find-next-greater-number-set-digits/
*
* @author shivam.maharshi
*/
public class NextBigNumber {
static int[] num;
public static void getNext() {
if (num == null) {
System.out.println("Invalid input.");
return;
}
if (num.length == 1) {
System.out.println(num[0]);
return;
}
int i = num.length - 2;
outer: while (i >= 0) {
for (int j = num.length - 1; j > i; j--) {
if (num[i] < num[j]) {
swap(i, j);
break outer;
}
if (i == 0 && j == 1) {
System.out.println("This is the maximum number.");
return;
}
}
i--;
}
int j = num.length - 1;
++i;
while (i < j) {
swap(i, j);
--j;
++i;
}
printNum(num);
}
private static void swap(int i, int j) {
int temp = num[i];
num[i] = num[j];
num[j] = temp;
}
private static void printNum(int[] num) {
String res = "";
for (int i = 0; i < num.length; i++) {
res += num[i];
}
System.out.println(res);
}
public static void main(String[] args) {
NextBigNumber.num = new int[] { 1, 2, 3, 4, 5 };
int i = 120;
while (i != 0) {
--i;
System.out.println(i);
NextBigNumber.getNext();
}
}
}