371. Sum of Two Integers
Pick One
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
解法:
思路:
使用“与”与“异或”运算,其中按位“与”只是得到了进位信息,“异或”运算则是没有进位信息的“伪加法”。因此,要同时充分利用这两种运算求解加法运算。
public int getSum(int a, int b) {
int carry = 0;
while(b!=0) {
// 记录产生进位的位
carry = a&b;
// 伪加法,没有进位的加法
a = a^b;
// 将carry左移,移到更高的一位
b = carry << 1;
}
return a;
}
实际上,每次循环末尾得到的进位的b,将会在下一环循环和a再做加法,只有当b为零的时候结束循环。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。