Minimum Bit Flips to Convert Number - Problem
Imagine you have two numbers represented in binary, and you want to transform one into the other by flipping individual bits. A bit flip means changing a 0 to 1 or a 1 to 0 at any position in the binary representation.
For example, if you have the number 7 (binary: 111), you can:
- Flip the rightmost bit:
111→110(becomes 6) - Flip the middle bit:
111→101(becomes 5) - Even flip a leading zero:
111→10111(becomes 23)
Given two integers start and goal, your task is to find the minimum number of bit flips needed to convert start into goal.
This is essentially asking: how many positions have different bits between the two numbers?
Input & Output
example_1.py — Basic case
$
Input:
start = 10, goal = 7
›
Output:
3
💡 Note:
10 in binary is 1010, 7 in binary is 0111. Comparing bit by bit: positions 0, 2, and 3 are different (1≠1, 1≠1, 1≠0), so we need 3 flips.
example_2.py — Same numbers
$
Input:
start = 3, goal = 4
›
Output:
3
💡 Note:
3 in binary is 011, 4 in binary is 100. All three bit positions are different (0≠1, 1≠0, 1≠0), requiring 3 flips.
example_3.py — Edge case
$
Input:
start = 0, goal = 0
›
Output:
0
💡 Note:
Both numbers are the same, so no bit flips are needed.
Visualization
Tap to expand
Understanding the Visualization
1
Identify the patterns
Convert both numbers to binary and align them
2
Find differences
Use XOR to highlight positions where bits differ
3
Count the switches
Each '1' in the XOR result represents a bit flip needed
4
Return the count
The total number of '1's is our answer
Key Takeaway
🎯 Key Insight: XOR operation naturally identifies all positions where two numbers differ, and counting set bits gives us the exact number of flips needed.
Time & Space Complexity
Time Complexity
O(log(max(start, goal)))
XOR is O(1), bit counting is O(number of bits) which is logarithmic
⚡ Linearithmic
Space Complexity
O(1)
Only using constant extra space
✓ Linear Space
Constraints
- 0 ≤ start, goal ≤ 109
- Both numbers fit in 32-bit signed integers
- Time limit: 1 second per test case
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code