Bird
Raised Fist0

Consider this iterative bitwise sum implementation. Which line contains a subtle bug that causes incorrect results for negative inputs?

medium🐞 Bug Identification Q7 of Q15
Bit Manipulation - Sum of Two Integers Without + Operator
Consider this iterative bitwise sum implementation. Which line contains a subtle bug that causes incorrect results for negative inputs?
AThe carry calculation missing parentheses around (a & b)
BThe while loop condition should be 'while a != 0' instead of 'while b != 0'
CThe return statement missing sign correction for negative numbers
DThe masking with MASK should be applied after the while loop
Step-by-Step Solution
Solution:
  1. Step 1: Identify handling of negative numbers

    Python integers are unbounded; masking intermediate results is correct, but final result must convert back to signed integer.
  2. Step 2: Check return statement

    Return statement lacks sign correction (e.g., 'return a if a <= 0x7FFFFFFF else ~(a ^ MASK)') causing wrong negative outputs.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Missing sign fix causes incorrect negative sums [OK]
Quick Trick: Final sign fix needed after masking [OK]
Common Mistakes:
MISTAKES
  • Ignoring sign conversion after masking
Trap Explanation:
PITFALL
  • Candidates think masking alone handles negatives, missing final sign fix.
Interviewer Note:
CONTEXT
  • Tests subtle bug detection in bitwise sum handling negatives
Master "Sum of Two Integers Without + Operator" in Bit Manipulation

3 interactive learning modes - each teaches the same concept differently

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Bit Manipulation Quizzes