CodeForces 627A : XOR Equation(位運算性質)

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 ≤ 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.

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 對的個數爲 2n

此外,此題還有三個會 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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章