The solution method returns null if there are no solutions. If there is a solution, it returns a (for only one solution). You can get b by doing s - a or x ^ a .
If there is a solution, the total number of solutions (in long ) is 2 degrees. Long.bitCount(x) .
For example, the solution found for s = 24 , x = 6 is a = 9 , b = 15 . In binary format:
9 = 1001 15 = 1111
These numbers differ in two positions, therefore, in the general case, there are Math.pow(2, 2) = 4 solutions. You can get all possible solutions by replacing bits a with corresponding bits b for some or all of these positions.
This gives 3 more solutions.
11 = 1011 13 = 1101 15 = 1111 13 = 1101 11 = 1011 9 = 1001
Here is the code:
public static Long solution(long s, long x) { return recursive(s, x, false); } private static Long recursive(long s, long x, boolean carry) { boolean s1 = (s & 1) == 1; boolean x1 = (x & 1) == 1; if ((s1 == x1) == carry) return null; if ((s == 0 || s == -1) && (x == 0 || x == -1)) return s; Long a; if (x1) return (a = recursive(s >> 1, x >> 1, carry)) == null ? null : a << 1; if ((a = recursive(s >> 1, x >> 1, false)) != null) return a << 1; if ((a = recursive(s >> 1, x >> 1, true)) != null) return 1 + (a << 1); return null; }
I decided not to write a method to return a HashSet all solutions, since in some cases these sets would be massive. However, you can write a method to create all possible solutions without storing them immediately in memory. See, for example, Generating All Binary Numbers Based on a Pattern