?LeetCode刷題實(shí)戰(zhàn)371:兩整數(shù)之和
Given two integers a and b, return the sum of the two integers without using the operators + and -.
示例
示例 1:
輸入: a = 1, b = 2
輸出: 3
示例 2:
輸入: a = -2, b = 3
輸出: 1
解題
class Solution {
public:
int getSum(int a, int b) {
int result = a^b;
//判斷是否需要進(jìn)位
int forward = (a&b) <<1;
if(forward!=0){
//如有進(jìn)位,則將二進(jìn)制數(shù)左移一位,進(jìn)行遞歸
return getSum(result,forward);
}
return result;
}
};
評(píng)論
圖片
表情
