c++ 位运算 加减

Modified on: Sat, 18 May 2019 00:14:52 +0800 热度: 919 度
#include <iostream>
using namespace std;
int add(int a,int b)
{
    int sum = a ^ b;
    int carray = (a & b) << 1;
    while(carray != 0)
    {
        int a = sum;
        int b = carray;
        sum = a ^b;
        carray = (a & b) << 1;
    }
    return sum;
}
int dec(int a,int b)
{
    int sub=add(~b,1);
    return add(a,sub);
}
int main(int argc, const char * argv[]) {
    while(1)
    {
        int a,b;
        cin>>a>>b;
        cout<<"加法:"<<add(a,b)<<"减法:"<<dec(a,b)<<endl;
    }
    return 0;
}

添加新评论