-
-
Save anonymous/74c0c73802361ee89fe73a3b48967ea6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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