题解 | #不用加减乘除做加法#
不用加减乘除做加法
http://www.nowcoder.com/practice/59ac416b4b944300b617d4f7f111b215
carry表示进位,notCarry表示非进位,异或(^)得到非进位,与(&)得到进位并向左移位,循环直到不存在进位,那么非进位就是所求值。 示例:
carry | notCarry |
---|---|
111 | 101 |
1010 | 0010 |
0100 | 1000 |
0000 | 1100 |
function Add(num1, num2)
{
let carry = num1;
let notCarry = num2;
if (num1 == 0 || num2 == 0) {
return num1 || num2
}
while (carry != 0) {
let temp = carry ^ notCarry
// <<运算优先级大于&
carry = (carry & notCarry) << 1
notCarry = temp
}
return notCarry
}
module.exports = {
Add : Add
};