Example 1
- Input
- a = 1, b = 2
- Output
- 3
Plain addition gives 1 + 2 = 3, rebuilt here with bitwise steps.
Compute a + b using only bitwise operators, never + or -. The method mirrors how hardware adders combine a carry-free sum with a shifted carry until nothing carries.
Given two integers a and b, return their sum without using the operators + and -.
Think like a hardware adder: one bitwise pass adds every position with no carry, a second pass finds where carries arise, and the two results are combined until no carry remains.
+ nor - may appear in the solution logic.Plain addition gives 1 + 2 = 3, rebuilt here with bitwise steps.
The bits of 2 and 3 combine with one carry round to reach 5.
Mixed signs flow through the same carry loop to give -2 + 3 = 1.
Opposite values cancel. In a 32-bit carry loop, the carry travels through the run of 1 bits and then falls outside the word; the remaining word is zero.
A zero second operand requires no carry rounds or unit transfers. Python must still return the signed value when decoding the masked initial word.
At one bit position, two different bits produce a sum bit of 1 and no carry; two 1 bits produce a sum bit of 0 and a carry into the next position. XOR gives all carry-free sum bits at once, while AND followed by a left shift places all carries into their destination positions. For a = 1 and b = 2, no positions overlap, so XOR immediately gives 3 and the carry is zero. Negative inputs require the same finite 32-bit representation throughout.
Reveal Unit Step Loop: intuition, complexity, and code
a ^ b adds every bit position while ignoring carries.(a & b) << 1 marks exactly where carries appear, so repeating xor-then-carry until the carry is zero finishes the addition.a = -2, b = 3 must flow through the same carry loop and yield 1.0xFFFFFFFF mask or the carry loop never terminates on negatives.a = -1, b = 1 must give 0.Xor adds without carry while and-plus-shift computes the carry: looping those two steps simulates the adder circuit inside every processor.