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: 111110 (becomes 6)
  • Flip the middle bit: 111101 (becomes 5)
  • Even flip a leading zero: 11110111 (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
Binary Switch TransformationCurrent State (start = 10):1010Target State (goal = 7):0111Differences (XOR result = 13):1101← Flips neededSolution Process:1. XOR the two numbers: 1010 ⊕ 0111 = 11012. Count the '1' bits in result: 1101 has 3 ones3. Answer: 3 bit flips required
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

n
2n
Linearithmic
Space Complexity
O(1)

Only using constant extra space

n
2n
Linear Space

Constraints

  • 0 ≤ start, goal ≤ 109
  • Both numbers fit in 32-bit signed integers
  • Time limit: 1 second per test case
Asked in
Google 15 Amazon 12 Meta 8 Microsoft 6
28.0K Views
Medium Frequency
~8 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen