BItwise运算符,左移和右移如何工作

时间:2019-12-16 17:18:23

标签: c# bitwise-operators

public class Solution {
    public int GetSum(int a, int b) {
        while(b != 0) {
            int carry = a & b;
            a = a ^ b;
            b = carry << 1;
        }
        return a;
    }
}

所以问题是在不使用算术运算符的情况下将两个数相加,我在leetcode的“讨论”部分找到了一个解决方案,但是我不确定进位变量的工作原理

1 个答案:

答案 0 :(得分:2)

public class Solution {
    public int GetSum(int a, int b) {
       // Iterate till there is no carry 
        while(b != 0) {
            // carry now contains common 
            // set bits of a and b 
            int carry = a & b;
             // Sum of bits of a and  
            // b where at least one  
            // of the bits is not set 
            a = a ^ b;
            // Carry is shifted by  
            // one so that adding it  
            // to a gives the required sum 
            b = carry << 1;
        }
        return a;
    }
}
  

示例

当您这样调用sum函数时

GetSum(60, 13)
/* 60 = 0011 1100 */  
/* 13 = 0000 1101 */

while(b != 0)(它的while循环,它将一直循环直到b变为0)

int carry = a & b;; // a=60 & 13 

将成为12 /* 12 = 0000 1100 */

a = a ^ b;

将成为49 /* 49 = 0011 0001 */

b = carry << 1;

将由于24而成为Binary Left Shift Operator(<<)。左操作数的值向左移动right operand指定的位数,它将像我解释的那样循环并计算continue