Skip to content

Instantly share code, notes, and snippets.

Created November 2, 2017 18:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/74c0c73802361ee89fe73a3b48967ea6 to your computer and use it in GitHub Desktop.
Save anonymous/74c0c73802361ee89fe73a3b48967ea6 to your computer and use it in GitHub Desktop.
import java.util.Arrays;
public class MyClass {
public static 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[i-1]) 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[i-1]) j--;
// Exchange the digits at location i and j
char tmp = cArr[j];
cArr[j] = cArr[i-1];
cArr[i-1] = 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;
}
public static void main(String args[]) {
int x=10;
int y=25;
int z=x+y;
System.out.println("Sum of x+y = " + nextGreaterElement(19999999));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment