forked from IDeserve/learn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNextHigherNumber.java
95 lines (73 loc) · 1.53 KB
/
NextHigherNumber.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package questions.virendra;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
public class NextHigherNumber {
public static void nextHigherNumber(Integer num)
{
Integer nextNum = num, temp = num;
ArrayList<Integer> digits = new ArrayList<Integer>();
while(temp > 0 )
{
int digit = temp%10;
temp = temp/10;
digits.add(digit);
}
int j = 0;
int i = j+1;
if(digits.size() > 1)
{
while(i < digits.size())
{
if (digits.get(i) < digits.get(j))
{
break;
}
j++;
i++;
}
if(i>=digits.size())
{
System.out.println("None");
return;
}
//where to swap
int swapLoc = 0;
j=0;
while(j<i)
{
if(digits.get(j) > digits.get(i))
break;
j++;
}
//swap last and i
int dg = digits.get(i);
digits.set(i, digits.get(j));
digits.set(j, dg);
//Collections.sort(digits.subList(i+1, digits.size()));
}
List<Integer> subList = digits.subList(0, i);
System.out.println(subList);
Collections.sort(subList);
int m = digits.size() - 1;
while(m >= i)
{
System.out.print(digits.get(m));
m--;
}
m = 0;
while(m < subList.size())
{
System.out.print(subList.get(m));
m++;
}
System.out.println();
}
public static void main(String args[])
{
nextHigherNumber(12543);
nextHigherNumber(4132);
nextHigherNumber(1234);
nextHigherNumber(32841);
}
}