-
Notifications
You must be signed in to change notification settings - Fork 1
/
7thJune(I).java
64 lines (46 loc) · 1.23 KB
/
7thJune(I).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
public class NextGreaterElement3 {
static int NextGreaterElement(int n){
String str = String.valueOf(n); // typecast to string
char[] arr = str.toCharArray(); // make a character array
// store 2nd last digit ...
int i = arr.length-2;
// store last digit
int k = arr.length-1;
while(i>=0 && arr[i]>=arr[i+1]){
i--;
}
if(i==-1){
return -1;
}
while(arr[i]>=arr[k]){
k--;
}
// swap
char temp = arr[i];
arr[i]= arr[k];
arr[k]=temp;
// concatination of string from the array
String res = "";
for(int j =0; j<=i;j++){
res+=arr[j];
}
for(int j =arr.length-1;j>i; j--){
res+=arr[j];
}
// type conversion
long output = Long.parseLong(res);
int output_1;
if(output>Integer.MAX_VALUE){
return -1;
}
else{
output_1 = (int)output;
}
return output_1;
}
public static void main(String[] args) {
int num = 21;
int res = NextGreaterElement(num);
System.out.println(res);
}
}