File tree Expand file tree Collapse file tree 1 file changed +22
-0
lines changed
Expand file tree Collapse file tree 1 file changed +22
-0
lines changed Original file line number Diff line number Diff line change 1+ # Time Complexity: O(1) - fixed 32-bit operations, at most 32 iterations
2+ # Space Complexity: O(1) - only uses a few integer variables
3+
4+ class Solution :
5+ def getSum (self , a : int , b : int ) -> int :
6+ # 32-bit mask to keep numbers within range
7+ mask = 0xFFFFFFFF
8+ # max value for a signed 32-bit integer (2^31 - 1)
9+ MAX = 0x7FFFFFFF
10+
11+ # keep going until there's no carry left
12+ while b != 0 :
13+ # carry is AND operation, then shift left
14+ carry = (a & b ) << 1
15+ # XOR does the addition, keep it within 32 bits
16+ a = (a ^ b ) & mask
17+ # carry becomes the new b (loop continues if carry exists)
18+ b = carry & mask
19+
20+ # if a is greater than MAX, it's actually a negative number in 32-bit terms
21+ # convert it to proper negative representation
22+ return a if a <= MAX else ~ (a ^ mask )
You can’t perform that action at this time.
0 commit comments