File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ //Given a positive integer n, find the smallest integer which has exactly
2+ //the same digits existing in the integer n and is greater in value than n.
3+ //If no such positive integer exists, return -1.
4+
5+ //Note that the returned integer should fit in 32-bit integer,
6+ //if there is a valid answer but it does not fit in 32-bit integer, return -1.
7+
8+ //Example 1:
9+
10+ //Input: n = 12
11+ //Output: 21
12+
13+ //Example 2:
14+
15+ //Input: n = 21
16+ //Output: -1
17+
18+ import java .util .Scanner ;
19+
20+ public class NextGreaterElement {
21+
22+ public static void main (String [] args ) {
23+ Scanner sc = new Scanner (System .in );
24+
25+ int n = sc .nextInt ();
26+ long ans = nextGreaterElement (n );
27+ System .out .println (ans );
28+ }
29+
30+ private static long nextGreaterElement (int n ) {
31+ // convert interger to string and than string to character array
32+ char arr [] = (Integer .toString (n )).toCharArray ();
33+
34+ // firstly find first lower element from left
35+ int i = arr .length -2 ;
36+ while (i >=0 && arr [i ]>=arr [i +1 ])
37+ i --;
38+ // according top test case returning the -1
39+ if (i ==-1 )
40+ return -1 ;
41+
42+ int k = arr .length -1 ;
43+ while (arr [i ]>=arr [k ])
44+ k --;
45+ // swap the values of ith and kth
46+ char temp = arr [i ];
47+ arr [i ] = arr [k ];
48+ arr [k ] = temp ;
49+
50+ // Storing the values of 0 to i in res
51+ String res = "" ;
52+ for (int j =0 ;j <=i ;j ++)
53+ res +=arr [j ];
54+ // for nearest greater integer store it in the reverse order
55+ for (int j =arr .length -1 ;j >i ;j --)
56+ res +=arr [j ];
57+
58+
59+ // typecast to Long
60+ long ans = Long .parseLong (res );
61+ if (ans <=2147483647 )
62+ return (int ) ans ;
63+ else
64+ return -1 ;
65+
66+ }
67+
68+ }
You can’t perform that action at this time.
0 commit comments