Add Without Plus

Add Without Plus

Hard Programming Interview Algorithms 22 views
Explanation Complexity

Problem Statement

Consider {x}. Add them without using + or -. Use bit operations and output sum.

Input Format

One line: a b.

Output Format

One integer sum.

Example

5 7
12

Constraints

-10^9

Input / Output Format

Input Format
One line: a b.
Output Format
One integer sum.
Constraints
-10^9

Examples

Input:
5 7
Output:
12

Example Solution (Public)

Programming Interview
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))

Official Solution Code

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))
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.