美文网首页
371 Sum of Two Integers

371 Sum of Two Integers

作者: crazydane | 来源:发表于2017-11-14 22:19 被阅读0次

计算a,b之和。但不能使用 + 或者 -

考点,bit运算符
http://www.jianshu.com/p/7e00102bf8ad
http://blog.gainlo.co/index.php/2016/07/19/3sum/


”或“运算 |

int a  = 2 //10;
int b = 3 //11;
int c = a|b;
System.out.println(c);  //result is : 3 /11

“与”运算 &

int a  = 2; //10
int b = 3;  //11
int c = a&b;
System.out.println(c);   //result is : 2 //10

“异或”运算a^b

int a  = 2; //10
int b = 3;  //11
int c = a^b;
System.out.println(c);   //result is : 1 //01
def getSum(a, b):
    return a if b == 0 else getSum(a ^ b, (a & b) << 1)
int add(int a , int b)
{
    int sum = a;
    
    /*直到进位的结果为0*/
    while(b != 0)
    {
        sum = a ^ b; /*不考虑进位的和,用异或运算求和;*/
        b = (a & b) << 1; /*只考虑进位的产生值*/
        a = sum;
    }//while
    return sum;
}

正常101011 - 100001
101011 ^ 100001 = 001010
101011 & 100001 =100001

101011
  • 100001
    = 001010(不考虑进位)
    (101011 & 100001) = 100001(表明有两个位置有进位)
    左移一位表示进位。000010,然后一直加直到完全没有进位。

不用额外变量交换两个整数的值

a = 101
b = 110
a = a^b = 011
b = a^b = 101
a = a^b = 110

相关文章

网友评论

      本文标题:371 Sum of Two Integers

      本文链接:https://www.haomeiwen.com/subject/ookqvxtx.html