Minimum bit flip to convert number


2220. Minimum Bit Flips to Convert Number – LeetCode


Problem Statement

Given two integers start and goal, return the minimum number of bit flips required to convert start to goal.

A bit flip changes a 0 to 1 or a 1 to 0.


Examples

Example 1:

Input: start = 10, goal = 7
Output: 3
Explanation: 
Binary of 10 = 1010
Binary of 7  = 0111
Bits different at 3 positions → 3 flips required

Example 2:

Input: start = 3, goal = 4
Output: 3
Explanation:
3 = 011, 4 = 100 → All 3 bits differ

Constraints


Intuition

To convert start to goal, we need to find out how many bits are different between them.

This can be directly computed by:


Approach: XOR + Set Bit Count (Brian Kernighan's Algorithm)

  1. Perform XOR between start and goal → stores difference bits

  2. Count number of 1s in XOR result using:

    • x = x & (x - 1) to remove the lowest set bit each time
  3. Return the count


Java Code

class Solution {
    public int minBitFlips(int start, int goal) {
        int temp = start ^ goal;
        int cnt = 0;
        while (temp > 0) {
            temp = temp & (temp - 1); // Remove the lowest set bit
            cnt++;
        }
        return cnt;
    }
}

Time and Space Complexity

Metric Value
Time Complexity O(log n) (max 32 loops)
Space Complexity O(1)
Explanation Each iteration removes one set bit, max 32 bits for int

Dry Run

Input: start = 10, goal = 7


Conclusion

This problem is a direct application of bitwise XOR and set bit counting.

It highlights key concepts:

It's an excellent example of applying bit manipulation to solve real problems with constant space and logarithmic time.