Add Without Plus
Programming Interview
Hard
4 views
Problem Description
Consider {x}. Add them without using + or -. Use bit operations and output sum.
Input Format
One line: a b.
Output Format
One integer sum.
Official Solution
import sys
p=sys.stdin.read().strip().split()
if len(p)<2: sys.exit(0)
a=int(p[0]); b=int(p[1])
mask=0xFFFFFFFF
while b & mask:
carry=(a & b) & mask
a=(a ^ b) & mask
b=(carry << 1) & mask
if a>>31 & 1:
a=~(a ^ mask)
sys.stdout.write(str(a))
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!