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)?
The first line of the input contains two integers s and x (2 ≤ s ≤ 1012, 0 ≤ x ≤ 1012), the sum and bitwise xor of the pair of positive integers, respectively.
Print a single integer, the number of solutions to the given conditions. If no solutions exist, print 0.
题意:
a+b的和是s,a^b=x,输入s和x,问a和b的组合数
分析:
For any two integers a and b, we have , where
is the xor and a&b is the bitwise AND. This is because
is non-carrying binary addition. Thus, we can find a&b = (s - x) / 2 (if this is not an integer, there are no solutions).
Now, for each bit, we have 4 cases: , and
. If
, then ai = bi, so we have one possibility: ai = bi = ai&bi. If
, then we must have ai&bi = 0 (otherwise we print 0), and we have two choices: ai = 1 and bi = 0 or vice versa. Thus, we can return 2n, where n is the number of one-bits in x. (Remember to subtract 2 for the cases a = 0 or b = 0 if necessary.)
Runtime:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int main()
{
ll sum,x;
cin>>sum>>x;
ll a=(sum-x)/2;
if(a<0||a*2+x!=sum||(a&x)!=0){
cout<<0<<endl;return 0;
}
int t=0;
while(x){
t+=(x&1);
x>>=1;
}
ll ans=1ll<<t;
if(a==0)ans-=2;
cout<<ans<<endl;
}