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.
9 5
4
3 3
2
5 2
0
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 Xor b的值,问你满足条件的(a, b)有多少个。
思路:a + b == (a Xor b) + (a & b) * 2。然后枚举每一位就可以了。
AC代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <map>
#include <string>
#define CLR(a, b) memset(a, (b), sizeof(a))
using namespace std;
typedef long long LL;
const int MAXN = 2*1e5+10;
const int INF = 0x3f3f3f3f;
int main()
{
LL s, x; cin >> s >> x;
//a + b = (a Xor b) + (a & b) * 2
LL ans = 0;
if((s - x) >= 0 && (s - x) % 2 == 0) {
LL Andsum = (s - x) >> 1;
int cnt = 0; bool flag = true;
if(s == x) ans = -2;
while(x) {
if(x & 1){
cnt++;
if(Andsum & 1) flag = false;
}
if(!flag) break;
x >>= 1; Andsum >>= 1;
}
if(!flag) ans = 0;
else ans += (1LL<<cnt);
}
cout << ans << endl;
return 0;
}