题解:P1001 A+B Problem

· · 题解

题解:P1001 A+B Problem

首先我们需要知道三个性质。

性质 1 的证明:
对于 a,b 在二进制下的每一位都有四种情况。

发现以上四种情况都成立。

很显然,性质 2,3 成立。
有了这三条性质,我们就可以对 a,b 一直进行变换,直到 a=0b=0 为止。
代码实现:

#include<bits/stdc++.h>
using namespace std;
int add(int a,int b){
    if(a==0) return b;
    if(b==0) return a;
    return add(a^b,2*(a&b));
}
int main(){
    int a,b;
    cin>>a>>b;
    cout<<add(a,b);
    return 0;
}