2220. Minimum Bit Flips to Convert Number

Dare2Solve

Dare2Solve

2220. Minimum Bit Flips to Convert Number
SAMSUNG 49-Inch Odyssey G9
SAMSUNG 49-Inch Odyssey G9
Because earth is not flat

Description

The problem is about determining the minimum number of bit flips required to convert one number (start) to another (goal). A bit flip means changing a 0 to 1 or vice versa in the binary representation of the numbers.

Intuition

To find out how many bits differ between two numbers, we can use the XOR operation (^). The XOR operation returns a number where the bits are set to 1 only if the corresponding bits of the two numbers are different. By counting the number of set bits (1s) in the result, we can determine how many bit flips are required.

Approach

  1. Compute the XOR of start and goal. This gives a number where each bit represents whether the bits in that position differ between start and goal.
  2. Count the number of 1s in the result of the XOR operation. This can be done efficiently using a loop that continuously removes the least significant 1 bit from the number.
  3. The number of set bits is the number of bit flips required.

Steps:

Complexity

Time Complexity:

O(k), where k is the number of set bits in the XOR of start and goal. In the worst case, it could be O(log n) where n is the size of the integer (since each bit can be flipped).

Space Complexity:

O(1), as only a constant amount of space is used.

Code

C++

class Solution {
public:
    int minBitFlips(int start, int goal) {
        int num = start ^ goal; // XOR to find differing bits
        return countSetBits(num);
    }

private:
    int countSetBits(int num) {
        int count = 0;
        while (num != 0) {
            num = num & (num - 1); // Clear the least significant set bit
            count++;
        }
        return count;
    }
};

Python

class Solution:
    def minBitFlips(self, start: int, goal: int) -> int:
        num = start ^ goal  # XOR to find differing bits
        return self.countSetBits(num)

    def countSetBits(self, num: int) -> int:
        count = 0
        while num != 0:
            num = num & (num - 1)  # Clear the least significant set bit
            count += 1
        return count

Java

class Solution {
    public int minBitFlips(int start, int goal) {
        int num = start ^ goal; // XOR to find differing bits
        return countSetBits(num);
    }

    private int countSetBits(int num) {
        int count = 0;
        while (num != 0) {
            num = num & (num - 1); // Clear the least significant set bit
            count++;
        }
        return count;
    }
}

JavaScript

var minBitFlips = function (start, goal) {
    let num = start ^ (goal);
    return countSetBits(num);
}
var countSetBits = (num) => {

    let count = 0;
    while (num != 0) {
        num = num & num - 1;
        count++;
    }
    return count;
}