友情支持
如果您觉得这个笔记对您有所帮助,看在D瓜哥码这么多字的辛苦上,请友情支持一下,D瓜哥感激不尽,😜
有些打赏的朋友希望可以加个好友,欢迎关注D 瓜哥的微信公众号,这样就可以通过公众号的回复直接给我发信息。
公众号的微信号是: jikerizhi 。因为众所周知的原因,有时图片加载不出来。 如果图片加载不出来可以直接通过搜索微信号来查找我的公众号。 |
371. Sum of Two Integers
Calculate the sum of two integers a and b, but you are not allowed to use the operator +
and -
.
Example 1:
Input: a = 1, b = 2
Output: 3
Example 2:
Input: a = -2, b = 3
Output: 1
思路分析
n = a ⊕ b 非进位和:异或运算
c = a & b << 1 进位:与运算+左移一位
这道题的关键有几点:
-
通过异或操作获取在不进位的情况下,各位的值;
-
通过相与加移位来来获取各个进位项;
-
重复上面的操作,直到进位项为 0 为止。
思考题:思考如何通过位运算来实现加减乘除?
-
一刷
-
二刷
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
* Runtime: 0 ms, faster than 100.00% of Java online submissions for Sum of Two Integers.
*
* Memory Usage: 37.9 MB, less than 6.67% of Java online submissions for Sum of Two Integers.
*
* @author D瓜哥 · https://www.diguage.com
* @since 2020-01-25 17:03
*/
public int getSumLoop(int a, int b) {
while (b != 0) {
int temp = a ^ b;
b = (a & b) << 1;
a = temp;
}
return a;
}
/**
* Runtime: 0 ms, faster than 100.00% of Java online submissions for Sum of Two Integers.
*
* Memory Usage: 37.7 MB, less than 6.67% of Java online submissions for Sum of Two Integers.
*/
public int getSum(int a, int b) {
return b == 0 ? a : getSum(a ^ b, (a & b) << 1);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
/**
* @author D瓜哥 · https://www.diguage.com
* @since 2024-09-16 19:56:29
*/
public int getSum(int a, int b) {
// 循环,当进位为 0 时跳出
while (b != 0) {
int c = (a & b) << 1; // c = 进位
a ^= b; // a = 非进位和
b = c; // b = 进位
}
return a;
}