Question
Given two integersÂ
a
 andÂb
, return the sum of the two integers without using the operatorsÂ+
 andÂ-
.
This is abit_manip question.
Idea
- We want to sum two numbers using bitwise operators
- The AND operator will only set bits that are both set in A and B
- The XOR operator will only set bits in A or B but not both
- When we add two numbers in binary (ex. 1+1 = 0 and 1 + 0 = 1) then we can observe that without carrying bits, A + B is A ^ B. We know when to carry a bit because A & B = 1 and this bit is shifted to the left by 1 place << 1. So the carry bit is (A & B) << 1
- We calculate the sum without carry, then calculate carry setting B to the carry bit until the carry bit is 0
- We also need to apply a mask on B when checking the while condition and when returning A if B > 0 due to python precision handling
MASK = 0xFFFFFFFF