627A - XOR Equation 数学

题目: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 and x (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, 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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值