371.Sum of Two Integers¶
Tags: Easy
Bit Manipulation
Links: https://leetcode.com/problems/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
class Solution {
public:
int getSum(int a, int b) {
while(b != 0)
{
unsigned int carry = a & b;
a = a ^ b;
b = carry << 1;
}
return a;
}
};
异或运算的特点是不进位加法,如果两数字对应位上是1则进位,所以用与运算解决,最后结果相加,继续递归调用,当没有进位时停止。
注意的是程序第6行,如果是int
类型,输入是1和-1时候会溢出。