Bird
Raised Fist0
Interview Prepbit-manipulationmediumFacebookAmazonGoogleBloomberg

Sum of Two Integers Without + Operator

Choose your preparation mode4 modes available
▶
Steps
setup

Initialize Inputs

We start with the input values a = 1 and b = 2. Both numbers are represented in 32-bit binary form for bitwise operations.

💡 Representing numbers in 32 bits allows us to visualize each bit's contribution to the sum and carry.
Line:def getSum(a: int, b: int) -> int:
💡 Understanding the binary representation of inputs is essential to follow the bitwise addition process.
📊
Sum of Two Integers Without + Operator - Watch the Algorithm Execute, Step by Step
Watching this step-by-step visualization reveals how addition can be decomposed into bitwise operations, making the process transparent and intuitive without relying on arithmetic operators.
Step 1/10
·Active fill★Answer cell
Start
A
0
1
=1
B
0
1
0
=2
Check if b == 0
A
0
1
=1
B
0
1
0
=2
💡 b is not zero, so continue
sum = a XOR b
A
0
1
=1
B
0
1
0
=2
──────
=
0
1
1
=3
💡 Bits where a and b differ are set in sum
carry = (a AND b) << 1
A
0
1
=1
B
0
1
0
=2
────────────────
=
0
0
0
0
0
0
0
0
=0
💡 No bits set in carry since a and b have no overlapping 1s
Check if carry == 0
A
0
1
1
=3
B
=0
💡 Carry is zero, so recursion ends
Return sum
A
0
1
1
=3
B
💡 Final sum is 3
No recursion needed (carry is zero)
A
0
1
1
=3
B
=0
💡 No recursion needed here
XOR operation detail
A
0
1
=1
B
0
1
0
=2
──────
=
0
1
1
=3
💡 Bits 30 and 31 differ between a and b, so XOR sets them
AND and shift left for carry
A
0
1
=1
B
0
1
0
=2
────────────────
=
0
0
0
0
0
0
0
0
=0
💡 No bits set in carry
Final sum
A
0
1
1
=3
B
💡 Sum of 1 and 2 is 3

Key Takeaways

✓ Addition can be performed using only bitwise XOR and AND operations combined with bit shifts.

This insight is difficult to grasp from code alone because the recursive interplay of sum and carry is abstract without visualization.

✓ XOR computes the partial sum ignoring carry, while AND followed by a left shift computes the carry bits that must be added next.

Seeing the bits set by XOR and AND operations side-by-side clarifies their distinct roles in addition.

✓ The recursion stops when carry becomes zero, meaning no further bit overflow exists.

Understanding the stopping condition is easier when you see carry bits vanish in the visualization.

Practice

(1/5)
1. Consider the following code snippet implementing the trie-based maximum XOR finder. Given the input array [2, 8], what is the return value of findMaximumXOR([2, 8])?
easy
A. 2
B. 8
C. 10
D. 0

Solution

  1. Step 1: Insert numbers 2 and 8 into trie

    2 in binary: 000...0010, 8 in binary: 000...1000. Trie stores bits for both numbers.
  2. Step 2: For each number, find max XOR partner

    For 2, try to find bits opposite to 2's bits in trie. At bit 3 (8's highest set bit), toggled bit exists, so max_xor |= 8. At bit 1, toggled bit exists, max_xor |= 2. Total max_xor = 10.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    2 XOR 8 = 10, which is maximum XOR [OK]
Hint: XOR of 2 and 8 is 10, max XOR found [OK]
Common Mistakes:
  • Confusing max_xor with input number
  • Off-by-one bit indexing
  • Returning XOR with self
2. You are given a sequence of integers representing bytes. You need to verify if this sequence forms a valid encoding where each character can be 1 to 4 bytes long, and continuation bytes must start with bits '10'. Which approach best guarantees an efficient and correct validation?
easy
A. Use a greedy approach that always assumes the longest possible character at each step.
B. Use a brute force approach checking each byte with nested conditions for all possible byte patterns.
C. Use dynamic programming to store valid prefixes and build up to the full sequence.
D. Use a single pass with a counter tracking how many continuation bytes are expected next.

Solution

  1. Step 1: Understand the problem constraints

    The problem requires validating UTF-8 encoding where each character can be 1 to 4 bytes, and continuation bytes must start with '10'.
  2. Step 2: Identify the approach that efficiently tracks continuation bytes

    The single pass with a continuation byte counter efficiently tracks how many continuation bytes are expected, ensuring correctness and O(n) time.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Single pass with counter matches UTF-8 rules and is optimal [OK]
Hint: Track continuation bytes with a counter for linear validation [OK]
Common Mistakes:
  • Assuming greedy longest match always works
  • Using DP unnecessarily complicates the problem
3. What is the time complexity of the Brian Kernighan's bit counting trick approach when counting set bits for all numbers from 0 to n?
medium
A. O(n * k) where k is the average number of set bits per number
B. O(n) because each number is processed in constant time
C. O(n * log n) because each number requires checking all bits
D. O(n^2) due to nested loops over bits and numbers

Solution

  1. Step 1: Identify loops and operations

    Outer loop runs n+1 times; inner loop runs as many times as set bits in each number.
  2. Step 2: Analyze average inner loop iterations

    Each iteration clears one set bit, so total inner loop iterations over all numbers is proportional to total set bits, roughly n * k.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Counting bits per number depends on number of set bits, not all bits [OK]
Hint: Time depends on total set bits, not total bits [OK]
Common Mistakes:
  • Assuming O(n log n) because of bit length
  • Thinking each number is constant time
  • Confusing nested loops as quadratic
4. Suppose the problem is extended to find the bitwise AND of all numbers in the range [left, right], but now left and right can be negative integers. Which modification to the optimal algorithm is necessary?
hard
A. Convert negative numbers to their 2's complement positive equivalents and then apply the algorithm.
B. Use a mask to limit the bit-length and shift both numbers until equal, considering sign bits.
C. No modification needed; the existing bit-clearing approach works for negative numbers.
D. Iterate through the entire range because bitwise AND with negatives is undefined.

Solution

  1. Step 1: Understand negative number representation

    Negative integers use 2's complement, so sign bits affect bitwise AND results.
  2. Step 2: Modify approach

    Masking to limit bit-length and shifting both numbers until equal handles sign bits correctly and finds common prefix.
  3. Step 3: Reject naive iteration

    Iterating entire range is inefficient and unnecessary; direct bitwise manipulation with sign awareness is needed.
  4. Final Answer:

    Option B -> Option B
  5. Quick Check:

    Handling sign bits requires masking and shifting, not naive bit-clearing [OK]
Hint: Handle sign bits with masking and shifting for negatives [OK]
Common Mistakes:
  • Assuming algorithm works unchanged for negatives
  • Trying to convert negatives to positives incorrectly
  • Iterating entire range for negatives
5. Suppose you want to check if a number is a power of two but the input can be negative or zero, and you want to handle 64-bit integers efficiently. Which modification to the bit manipulation approach is correct?
hard
A. Use the condition n > 0 and (n & (n - 1)) == 0 to handle all cases correctly.
B. Use n & (n + 1) == 0 to handle negative numbers as well.
C. Use floating point division to check if log2(n) is an integer for negative inputs.
D. Ignore negative inputs and only check positive numbers with n & (n - 1) == 0.

Solution

  1. Step 1: Understand input constraints

    Negative and zero inputs are not powers of two, so must be excluded explicitly.
  2. Step 2: Apply correct bit manipulation check

    Check n > 0 first, then use n & (n - 1) == 0 to verify exactly one set bit.
  3. Step 3: Confirm correctness for 64-bit integers

    This approach works efficiently for 64-bit integers as well, since bitwise ops are constant time.
  4. Final Answer:

    Option A -> Option A
  5. Quick Check:

    Explicit positive check avoids errors on zero/negative inputs [OK]
Hint: Always check n > 0 before bitwise power-of-two test [OK]
Common Mistakes:
  • Using incorrect bitwise operations
  • Ignoring negative inputs
  • Using floating point logs causing precision errors
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard