Last active
April 29, 2017 12:03
-
-
Save LuxXx/8189964c2b576f33551e44411b7fd41f to your computer and use it in GitHub Desktop.
[2017-04-26] Challenge #312 [Intermediate] Next largest number
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
package dailyprogrammer; | |
import java.util.Arrays; | |
/** | |
* https://www.reddit.com/r/dailyprogrammer/comments/67q3s6/20170426_challenge_312_intermediate_next_largest/ | |
* @author David | |
* | |
*/ | |
public class NextInt { | |
public static void main(String[] args) { | |
System.out.println(next(1234)); | |
System.out.println(next(1243)); | |
System.out.println(next(234765)); | |
System.out.println(next(19000)); | |
} | |
public static int next(int a) { | |
for (int i = a + 1; i < Integer.MAX_VALUE; i++) { | |
if (sameDigits(a, i)) return i; | |
} | |
throw new Error(); | |
} | |
public static boolean sameDigits(int a, int b) { | |
char[] ac = Integer.toString(a).toCharArray(); | |
Arrays.sort(ac); | |
char[] bc = Integer.toString(b).toCharArray(); | |
Arrays.sort(bc); | |
return equals(ac, bc); | |
} | |
public static boolean equals(char[] a, char[] b) { | |
if (a.length != b.length) return false; | |
for (int i = 0; i < a.length; i++) { | |
if (a[i] != b[i]) return false; | |
} | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment