Minimum Bit Flips to Convert Number

Pattern: Counting bits

easy

Each flip fixes one differing bit, and start ^ goal has a 1 exactly where they differ. So the answer is the number of set bits in start ^ goal.

The problem

A bit flip changes one bit of a number from 0 to 1 or 1 to 0. Given start and goal, return the fewest flips that turn start into goal. For example, 10 and 7 need 3, and 3 and 4 need 3.

The function name minBitFlips matches LeetCode. Use the link above for the exact statement and limits.

Think first

  • Which bits must change?
  • Which operator marks exactly the bits that differ?
  • How do you count set bits quickly?

Hints

    Brute force, and why it fails

    Compare the two numbers bit by bit over 32 positions. XOR plus popcount is the same idea in fewer steps.

    The key insight

    "How many positions differ" is the Hamming distance, and XOR turns it into "how many bits are set".

    Dry run

    1 0 1 00 
    0 1 1 11 

    start = 10 (1010) and goal = 7 (0111).

    Step 1 of 4

    The plan

    diff = start ^ goal, count = 0
    while diff != 0: diff = diff & (diff - 1); count = count + 1
    return count
    

    Complexity

    Time
    O(number of differing bits)
    Space
    O(1)

    At most 32 steps.

    Edge cases

    • Equal numbers: 0.
    • One of them 0: the popcount of the other.
    • Large values up to 10⁹: still at most 30 steps.
    I've built my logic, show the code

    Java

    class Solution {
        public int minBitFlips(int start, int goal) {
            int diff = start ^ goal, count = 0;     // 1s mark the bits that differ
            while (diff != 0) {
                diff &= diff - 1;                   // clear the lowest set bit
                count++;
            }
            return count;
        }
    }

    C++

    class Solution {
    public:
        int minBitFlips(int start, int goal) {
            unsigned int diff = static_cast<unsigned int>(start ^ goal);   // 1s mark the bits that differ
            int count = 0;
            while (diff != 0) {
                diff &= diff - 1;                   // clear the lowest set bit
                count++;
            }
            return count;
        }
    };

    Python

    class Solution:
        def minBitFlips(self, start: int, goal: int) -> int:
            diff, count = start ^ goal, 0           # 1s mark the bits that differ
            while diff:
                diff &= diff - 1                    # clear the lowest set bit
                count += 1
            return count

    Common mistakes

    • Counting bits of start - goal instead of start ^ goal.
    • Looping over a fixed 32 bits and checking each, which works but is longer.
    • Forgetting that flips are independent, so no order matters.

    Similar problems