标签:
This problem is a little confusing to me at first. But after I read some articles online, I got to know that it requires bitwise operations.
So basically, we need to use "^" to calculate the sum of two integers, and "&" << 1 to calculate the carry.
Here is recursive way.
1 public class Solution { 2 public int GetSum(int a, int b) { 3 if (b == 0) return a; 4 5 int sum = a ^ b; 6 int carry = (a & b) << 1; 7 8 return GetSum(sum, carry); 9 } 10 }
And here is iterative way.
public class Solution { public int GetSum(int a, int b) { while (b != 0) { int carry = (a & b); a = a ^ b; b = carry << 1; } return a; } }
注意这个while循环里面,需要我们先计算int carry = (a & b),不然会报错。
LeetCode 371 Sum of Two Integers
标签:
原文地址:http://www.cnblogs.com/wenchan/p/5751275.html