首页 > 代码库 > 371. Sum of Two Integers

371. Sum of Two Integers

题目

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.


分析

不用+ - 号求两个整数的和,用二进制运算(&, |, ~, ^)


解答

解法1:(我)

 1 public class Solution {
 2     public int getSum(int a, int b) {
 3         int c = a;
 4         int d = b;
 5         while ((c & d) != 0){
 6             int cc = c;
 7             c = c ^ d;
 8             d = (cc & d) << 1;
 9         }
10         return (c ^ d);
11 
12     }
13 }

解法2+:两种方法(递归、迭代),三种运算(加法、减法、相反数)

"&" AND operation, for example, 2 (0010) & 7 (0111) => 2 (0010)

"^" XOR operation, for example, 2 (0010) ^ 7 (0111) => 5 (0101)

"~" NOT operation, for example, ~2(0010) => -3 (1101) (参与运算的都是以补码的形式)

In bit representation, a = 0001, b = 0011,

First, we can use "and"("&") operation between a and b to find a carry.

carry = a & b, then carry = 0001

Second, we can use "xor" ("^") operation between a and b to find the different bit, and assign it to a,

Then, we shift carry one position left and assign it to b, b = 0010.

Iterate until there is no carry (or b == 0)

 1 // Iterative
 2 public int getSum(int a, int b) {
 3     if (a == 0) return b;
 4     if (b == 0) return a;
 5 
 6     while (b != 0) {
 7         int carry = a & b;
 8         a = a ^ b;
 9         b = carry << 1;
10     }
11     
12     return a;
13 }
14 
15 // Iterative
16 public int getSubtract(int a, int b) {
17     while (b != 0) {
18         int borrow = (~a) & b;
19         a = a ^ b;
20         b = borrow << 1;
21     }
22     
23     return a;
24 }
25 
26 // Recursive
27 public int getSum(int a, int b) {
28     return (b == 0) ? a : getSum(a ^ b, (a & b) << 1);
29 }
30 
31 // Recursive
32 public int getSubtract(int a, int b) {
33     return (b == 0) ? a : getSubtract(a ^ b, (~a & b) << 1);
34 }
35 
36 // Get negative number
37 public int negate(int x) {
38     return ~x + 1;
39 }

 

371. Sum of Two Integers