Problem: https://leetcode.com/problems/sum-of-two-integers/
This quiz is a bit of easier to solve with C language.
class Solution {
public:
int getSum(int a, int b) {
int c = 0;
int carry = 0;
for (int i = 0; i < 32; i ++) {
int aa = (a >> i) & 1;
int bb = (b >> i) & 1;
int cc = aa ^ bb ^ carry;
carry = (aa + bb + carry) / 2;
c = c | (cc << i);
}
return c;
}
};
The Python solution.
class Solution:
def getSum(self, a: int, b: int) -> int:
c = 0
carry = 0
for i in range(32):
x = (a >> i) & 1
y = (b >> i) & 1
z = x ^ y ^ carry
carry = x & y or x & carry or y & carry
c = (z << i) ^ c
return (c ^ 0x80000000) - 0x80000000
No comments:
Post a Comment