如果没有解决方案,solution 方法将返回 null。如果有解决方案,它会返回a(仅针对一种解决方案)。您可以通过s - a 或x ^ a 获得b。
如果存在解决方案,则解决方案的总数(在long 中)是Long.bitCount(x) 的2 次方。
例如,为s = 24、x = 6 找到的解决方案是a = 9、b = 15。
二进制:
9 = 1001
15 = 1111
这些数字在 2 个位置上不同,因此总共有 Math.pow(2, 2) = 4 个解决方案。您可以通过将a 的位与b 的相应位交换部分或全部这些位置来获得所有可能的解决方案。
这给出了 3 个进一步的解决方案。
11 = 1011 13 = 1101 15 = 1111
13 = 1101 11 = 1011 9 = 1001
代码如下:
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;
}
我决定不编写一个方法来返回所有解决方案的HashSet,因为这些集合在某些情况下会很大。但是,您可以编写一种方法来生成所有可能的解决方案,而无需一次将它们全部存储在内存中。例如,请参阅Generating all binary numbers based on the pattern