Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit a225135

Browse files
committedMay 29, 2025·
- Sum of Two Integers #284
1 parent 989fadc commit a225135

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
 

‎sum-of-two-integers/ayosecu.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
class Solution:
2+
"""
3+
- Time Complexity: O(1), <= 32 bit operation
4+
- Space Complexity: O(1)
5+
"""
6+
def getSum(self, a: int, b: int) -> int:
7+
# Using mask value for making 32 bit integer operation
8+
MASK = 0xFFFFFFFF
9+
MAX_INT = 0x7FFFFFFF
10+
11+
while b != 0:
12+
xor = (a ^ b) & MASK
13+
carry = ((a & b) << 1) & MASK
14+
a, b = xor, carry
15+
16+
# If a is overflow than MAX_INT (Negative Integer), return 2's compliment value
17+
return a if a <= MAX_INT else ~(a ^ MASK)
18+
19+
tc = [
20+
(1, 2, 3),
21+
(2, 3, 5)
22+
]
23+
24+
sol = Solution()
25+
for i, (a, b, e) in enumerate(tc, 1):
26+
r = sol.getSum(a, b)
27+
print(f"TC {i} is Passed!" if r == e else f"TC {i} is Failed! - Expected: {e}, Result: {r}")

0 commit comments

Comments
 (0)
Please sign in to comment.