Minimum Bit Flips to Convert Number - Problem
A bit flip of a number x is choosing a bit in the binary representation of x and flipping it from either 0 to 1 or 1 to 0.
For example, for x = 7, the binary representation is 111 and we may choose any bit (including any leading zeros not shown) and flip it. We can flip the first bit from the right to get 110, flip the second bit from the right to get 101, flip the fifth bit from the right (a leading zero) to get 10111, etc.
Given two integers start and goal, return the minimum number of bit flips to convert start to goal.
Input & Output
Example 1 — Basic Case
$
Input:
start = 10, goal = 7
›
Output:
3
💡 Note:
10 in binary is 1010, 7 in binary is 0111. We need to flip bits at positions 0, 1, and 3, so 3 flips total.
Example 2 — Same Numbers
$
Input:
start = 3, goal = 4
›
Output:
3
💡 Note:
3 in binary is 011, 4 in binary is 100. All three bit positions differ, so 3 flips needed.
Example 3 — Identical Numbers
$
Input:
start = 5, goal = 5
›
Output:
0
💡 Note:
Both numbers are identical, so no bit flips are needed.
Constraints
- 0 ≤ start, goal ≤ 109
Visualization
Tap to expand
Understanding the Visualization
1
Input Numbers
Two integers to compare bit by bit
2
Find Differences
Use XOR to identify differing bit positions
3
Count Flips
Number of differing positions equals minimum flips needed
Key Takeaway
🎯 Key Insight: XOR operation reveals exactly which bit positions differ between two numbers
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code