Bit Gap Between Codes
EasyBit ManipulationFree
Problem
Two door codes are stored as non-negative integers first and second. A technician wants to know how many individual bits would have to be toggled to turn one code into the other.
Return the number of bit positions at which first and second differ.
Example 1
- Input:
- first = 1, second = 4
- Output:
- 2
001 vs 100: positions 0 and 2 differ.
Example 2
- Input:
- first = 7, second = 7
- Output:
- 0
Constraints
- 0 ≤ first, second < 2^31
Hint
Show the first hint
Which bitwise operator produces a 1 exactly where two bits disagree?
Walkthrough
How to approach it
01Clarify before coding
- Do leading zeros count? Both numbers are compared on the same width; leading zeros on both sides never differ.
- Can the inputs be negative? No, both are below 2^31.
02Brute force
For each of the 31 positions extract bit i of both numbers and compare them.
Cost: O(31) time, O(1) space. Correct, but it does two extractions per position instead of letting one XOR do the comparison for all bits at once.
The rest of the walkthrough is in the app
The full walkthrough (key insight, step-by-step, dry run, complexity, edge cases, pitfalls, follow-ups) and solutions in Python and JavaScript are in the app, next to an editor and a terminal that runs your code against the tests.