627A - XOR Equation 数学

来源:互联网 发布:破解二维码软件 编辑:程序博客网 时间:2024/05/16 18:58

题目:627A - XOR Equation

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 andx (2 ≤ s ≤ 1012,0 ≤ x ≤ 1012), 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, print0.


题意:

a+b的和是s,a^b=x,输入s和x,问a和b的组合数

分析:

For any two integers a and b, we have , where is the xor anda&b is the bitwise AND. This is because is non-carrying binary addition. Thus, we can finda&b = (s - x) / 2 (if this is not an integer, there are no solutions).

Now, for each bit, we have 4 cases: , and. If, thenai = bi, so we have one possibility:ai = bi = ai&bi. If, then we must haveai&bi = 0 (otherwise we print0), and we have two choices: ai = 1 and bi = 0 or vice versa. Thus, we can return2n, where n is the number of one-bits in x. (Remember to subtract2 for the cases a = 0 orb = 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;}


0 0
原创粉丝点击