Skip to content

Latest commit

 

History

History
57 lines (38 loc) · 760 Bytes

371.两整数之和.md

File metadata and controls

57 lines (38 loc) · 760 Bytes

371. 两整数之和

url

题目

不使用运算符 +- ​​​​​​​,计算两整数 ​​​​​​​ab ​​​​​​​之和。

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

方法

code

js

let getSum = (a, b) => {
    return b === 0 ? a : getSum((a ^ b), (a & b) << 1);
};
console.log(getSum(1, 2));
console.log(getSum(-2, 3));

go

func getSum(a int, b int) int {
	if b == 0 {
		return a
	} else {
		return getSum(a ^ b, (a & b) << 1)
	}
}

java

class Solution {
    public int getSum(int a, int b) {
        return b == 0 ? a : getSum((a ^ b), (a & b) << 1);
    }
}