Leetcode 371. Sum of Two Integers
371. Sum of Two Integers
- Total Accepted: 10773
- Total Submissions:20732
- Difficulty: Easy
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.
思路:利用二进制的位运算实现数的加法。只要再找到进位,将其和XOR的结果加起来。
与操作&筛选出可以进位的位,然后将这些位左移1位,相当于是进位;异或操作^可以筛选出没有进位的位。
关于二进制运算原理,可以参考二进制位运算。
代码:
迭代:
1 class Solution { 2 public: 3 int getSum(int a, int b) { 4 int carry; 5 while(b){ 6 carry=(a&b)<<1; 7 a=a^b; 8 b=carry; 9 } 10 return a; 11 } 12 };
递归:
1 class Solution { 2 public: 3 int getSum(int a, int b) { 4 if(!b) return a; 5 return getSum(a^b,(a&b)<<1); 6 } 7 };
下面还有不用+和-实现的int范围内的减法和取相反数:
1 // Iterative 2 public int getSubtract(int a, int b) { 3 while (b != 0) { 4 int borrow = (~a) & b; 5 a = a ^ b; 6 b = borrow << 1; 7 } 8 9 return a; 10 } 11 12 // Recursive 13 public int getSubtract(int a, int b) { 14 return (b == 0) ? a : getSubtract(a ^ b, (~a & b) << 1); 15 } 16 17 // Get negative number 18 public int negate(int x) { 19 return ~x + 1; 20 }