92 - 两整数之和

题目

不使用运算符 + 和 - ,计算两整数 a 、b 之和。

示例 1:

输入: a = 1, b = 2 输出: 3

示例 2:

输入: a = -2, b = 3 输出: 1

解答

不能用运算符,就只能用位运算

作者:jalan 链接:https://leetcode-cn.com/problems/sum-of-two-integers/solution/wei-yun-suan-xiang-jie-yi-ji-zai-python-zhong-xu-y/

根据这位大佬的讲解,加法运算,可以拆解为无进位加法+进位

  • 无进位加法就是异或运算

  • 进位,是与运算+左移一位

循环这个过程,直到进位为0即可

var getSum = function (a, b) {
  while (b != 0) {
    let res = (a & b) << 1
    a = a ^ b
    b = res
  }
  return a
};

Runtime: 56 ms, faster than 37.77% of JavaScript online submissions for Sum of Two Integers.

Memory Usage: 33.8 MB, less than 80.00% of JavaScript online submissions for Sum of Two Integers.

func getSum(a int, b int) int {
    for b != 0 {
        res := (a & b) << 1
        a = a ^ b
        b = res
    }
    return a
}

Runtime: 0 ms, faster than 100.00% of Go online submissions for Sum of Two Integers.

Memory Usage: 1.9 MB, less than 100.00% of Go online submissions for Sum of Two Integers.

Last updated

Was this helpful?