LeetCode 371 Sum of Two Integers
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),不然会报错。
/*-------------------------------------------------------*/
现在用Python来试试,顺便整理一下原来的思路。Sum of two bits can be obtained by performing XOR (^) of the two bits. Carry bit can be obtained by performing AND (&) of two bits.但是在Python里面行不通了。从下面的算法可以看出来Python就不太好用了。但是还是记在这里权当是记录了。
下面这个代码来自于这两个博客
http://bookshadow.com/weblog/2016/06/30/leetcode-sum-of-two-integers/
https://www.hrwhisper.me/leetcode-sum-two-integers/
class Solution(object):
def getSum(self, a, b):
"""
:type a: int
:type b: int
:rtype: int
"""
MAX_INT = 0x7FFFFFFF
MIN_INT = 0x80000000
MASK = 0x100000000
while b:
a, b = (a ^ b) % MASK, ((a & b) << 1) % MASK
return a if a <= MAX_INT else ~((a % MIN_INT) ^ MAX_INT)
浙公网安备 33010602011771号