Question:
How to test if two numbers contain the same digits.
Answer:
Convert the numbers to Strings.
Convert the Strings to a Char Arrays.
Sort the Char Arrays.
Compare the Char Arrays.
Convert the Strings to a Char Arrays.
Sort the Char Arrays.
Compare the Char Arrays.
Code:
import java.util.Arrays; public class Example { public static void main(String[] args) { System.out.println("12 & 21: " + match(12,21)); System.out.println("123 & 321: " + match(123,321)); System.out.println("1231 & 2131: " + match(1231,2131)); System.out.println("876 & 886: " + match(876,866)); } public static boolean match(int a, int b) { String s1 = String.valueOf(a); char[] c1 = s1.toCharArray(); Arrays.sort(c1); String s2 = String.valueOf(b); char[] c2 = s2.toCharArray(); Arrays.sort(c2); return(Arrays.equals(c1,c2)); } }
Output:
$ java Example 12 & 21: true 123 & 321: true 1231 & 2131: true 876 & 886: false