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
Minimum Bit Flips to Convert Number INPUT start = 10 1 0 1 0 (binary: 1010) goal = 7 0 1 1 1 (binary: 0111) XOR = 10 ^ 7 = 13 1 1 0 1 (binary: 1101 - diff bits) ALGORITHM STEPS Brian Kernighan's Algorithm 1 XOR start and goal n = 10 ^ 7 = 13 (1101) 2 Count 1s in XOR result While n != 0, count++ 3 n = n & (n-1) Clears rightmost set bit Iterations: n=13(1101) --> 12(1100) count=1 n=12(1100) --> 8(1000) count=2 n=8(1000) --> 0(0000) count=3 n=0 --> STOP 4 Return count Total flips needed = 3 FINAL RESULT Bit Positions to Flip: start: 1 0 1 0 | | | v v v goal: 0 1 1 1 Output: 3 3 bit flips needed to convert 10 to 7 OK Key Insight: XOR of two numbers produces 1s only at positions where bits differ. Brian Kernighan's algorithm efficiently counts set bits by clearing the rightmost 1-bit in each iteration using n & (n-1). Time Complexity: O(k) where k = number of set bits. Space Complexity: O(1) TutorialsPoint - Minimum Bit Flips to Convert Number | Brian Kernighan's Algorithm
Asked in
Meta 15 Google 12 Microsoft 8 Amazon 6
78.1K Views
Medium Frequency
~10 min Avg. Time
2.8K 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