time limit per test2 seconds
memory limit per test256 megabytes
input standard input
output standard output
Two positive integers a and b have a sum of s and a bitwise XOR of x. How many possible values are there for the ordered pair (a, b)?
Input
The first line of the input contains two integers s and x (2 ≤ s ≤ , 0 ≤ x ≤ ), the sum and bitwise xor of the pair of positive integers, respectively.
Output
Print a single integer, the number of solutions to the given conditions. If no solutions exist, print 0.
Examples
Input
9 5
Output
4
Input
3 3
Output
2
Input
5 2
Output
0
Note
In the first sample, we have the following solutions: (2, 7), (3, 6), (6, 3), (7, 2).
In the second sample, the only solutions are (1, 2) and (2, 1).
解题思路
好一道数学题,先请出一个公式:
a + b == a ^ b + (a & b) * 2
粗略证明:
对 a,b 的每一位 ai,bi(1 <= i <= n),将 a + b 分为如下几部分的和:
1、ai != bi 的部分,和为 a ^ b;
2、ai == bi && ai == 1 的部分,和为 (a & b) * 2;
3、ai == bi && ai == 0 的部分,和为 0。
此题便是给你 a + b 的值 s ,和 a ^ b 的值 x,求满足 s 和 x 的 a、b 对的个数。
由上述公式,得 (s - x) / 2 == a & b 。可知,当 s < x || (s - x)%2 != 0 时直接判无解。
接下来就是玩智商的时候了,因为 bitwise XOR is non-carrying binary addition(按位异或是无进位的二进制加法),相加时进位,则亦或后该位为 0。
反之,若亦或后该位为 1,则相加时不进位,有 ai == 1 && bi == 0 || ai == 0 && bi == 1 两种可能;若亦或后该位为 0,仅有 ai == bi 一种可能。
所以,若 x 的二进制中有 n 位为 1,则 a、b 对的个数为 。
此外,此题还有三个会 WA 的点:
1、因为 a、b 为正整数,所以当 a&b 为 0 时,需减去 a==0 || b==0 的两种清况;
2、要用 1ll << one_bits 表示 long long 类型的 res,而非 1 << one_bits;
3、还是由按位异或无进位的性质,可知当 (a&b) & (a^b) != 0 时,也直接判无解。
AC代码
#include<iostream>
#include<cstdio>
using namespace std;
typedef long long ll;
ll sum,XOR,AND;
ll one_bits,res;
int main()
{
scanf("%lld%lld",&sum,&XOR);
AND=(sum-XOR)/2;
if((sum-XOR)%2!=0||sum<XOR||(AND&XOR)!=0)
printf("0\n");
else{
one_bits=0;
while(XOR){
if(XOR&1)
one_bits++;
XOR>>=1;
}
res=(1ll<<one_bits);
if(AND==0)
res-=2;
printf("%lld\n",res);
}
return 0;
}