silver-hands / sss

0 stars 0 forks source link

【Q098】面试题65. 不用加减乘除做加法 #98

Open fly0o0 opened 4 years ago

fly0o0 commented 4 years ago

面试题65. 不用加减乘除做加法

fly0o0 commented 4 years ago
/**
 * @param {number} a
 * @param {number} b
 * @return {number}
 */
var add = function(a, b) {
  while (b != 0) {
    // 进位,(a + b) % 2
    let carrySum = (a & b) << 1
    // 非进位,a + b
    let sum = a ^ b

    a = sum
    b = carrySum
  }

  return a
};