public int nextGreaterElement(int n) {
char[] cArr = String.valueOf(n).toCharArray();
// i is the leftmost digit that should be exchanged
int i = cArr.length  1;
while (i > 0 && cArr[i] <= cArr[i1]) i;
if (i <= 0) return 1;
// j is the digit that should be exchanged with digit at i
int j = cArr.length  1;
while (j >= i && cArr[j] <= cArr[i1]) j;
// Exchange the digits at location i and j
char tmp = cArr[j];
cArr[j] = cArr[i1];
cArr[i1] = tmp;
// Sort the digits from location i to the end
Arrays.sort(cArr, i, cArr.length);
try {
return Integer.parseInt(String.valueOf(cArr));
} catch (Exception e) {
// Intentionally left blank
}
return 1;
}
My Java solution with explanation in comments (3ms)


@RunRunCode
Hi I ran your code and want to discuss about one test case
Input : 1999999
Expected Output: 1Your output: 9199999
Can you explain why the leetcode test case is expecting wrong result when your answer is correct ?
Url https://gist.github.com/anonymous/74c0c73802361ee89fe73a3b48967ea6