Calculate the sum of two integers a and b, but you are not allowed to use the operator +
and -
.
Example:
Given a = 1 and b = 2, return 3.
public class Solution {
public int getSum(int a, int b) {
int ans = a^b;
int c = a&b;
while(c!=0){
c<<=1;
int ans_next = ans^c;
c = ans&c;
ans = ans_next;
}
return ans;
}
}
总结:这个题目很有意思,读完题目之后第一反应是应该使用位运算,但是具体怎么操作不太了解,因为很少写过位运算。同时这个题目的结题思路也是非常的巧妙,参考了一位前者的思路,首先通过“异或”计算得到一个如果没有进位的结果,再通过“与 ”计算得到哪些位存在进位。c保存进位的位置,如果存在进位的位置,那么将进位的位置左移一位再与上一次“异或”计算得到的结果“异或”计算。如果没有进位则直接输出,否则反复执行操作。