不使用运算符号实现加法和减法运算

167 阅读1分钟
- (void)addNum1:(NSInteger)num1 num2:(NSInteger)num2{

    //num1 + num2 = num1 ^ num2 + (num1 & num2) << 1

    //两个数字的和等于,两个数字的非进位加上进位部分左移一位之和,如此循环,直到没有进位得出结果,得出代码如下:

    NSInteger x = num1;

    NSInteger y = num2;

    while ( y != 0 ) {

        NSInteger temp = x ^ y;

        y = (x & y) << 1;

        x = temp;

    }

    NSLog(@"result = %ld",x);

    //两个数相减,负数的补码=其正数的反码+1,例如-15 = 10001111
    //越界的情况暂时没有考虑
}