题解:P1001 A+B Problem
huangboning · · 题解
考虑用位运算实现加法。
容易发现,异或就相当于对每一位进行不进位的加法。
那么如何处理进位?只有两数都为 1 才会产生进位,于是想到与运算,记得左移一位,表示乘二。
#include<bits/stdc++.h>
using namespace std;
int add(int a,int b){
while(b!=0){
int sum=a^b;//不进位的加法
int carry=(a&b)<<1;//进位
a=sum;
b=carry;
}
return a;
}
int a,b;
int main()
{
ios::sync_with_stdio(0);
cin>>a>>b;
cout<<add(a,b);
return 0;
}