Problem: Minimum Bit Flips to Convert Number (LeetCode Problem 2220)

Problem: Minimum Bit Flips to Convert Number (LeetCode Problem 2220)

In this problem, you are given two integers start and goal, and you need to determine the minimum number of bit flips required to convert start to goal. A bit flip changes a bit’s value from 0 to 1 or from 1 to 0.

Approach:

  1. XOR Operation: XOR (^) between start and goal will result in a binary number where each 1 represents a bit that is different between the two numbers.
  2. Count the Number of 1s: The number of 1s in the result of the XOR operation gives the number of bit flips required.

Solution in JavaScript:

// Function to calculate minimum bit flips to convert start to goal
function minBitFlips(start, goal) {
    // XOR the two numbers to get a result where 1s represent differing bits
    let xorResult = start ^ goal;

    // Count the number of 1s in the XOR result (which gives the number of bit flips)
    let count = 0;

    // Loop to count the number of 1s in the XOR result
    while (xorResult > 0) {
        count += xorResult & 1; // Check if the least significant bit is 1
        xorResult >>= 1; // Right shift the result to check the next bit
    }

    return count; // Return the number of bit flips required
}

// Example usage:

let start = 10; // Binary: 1010
let goal = 7;   // Binary: 0111

// Minimum bit flips required to convert 10 to 7
console.log(minBitFlips(start, goal)); // Output: 3

Explanation:

  1. XOR Operation: XOR between start and goal highlights all the differing bits. For example:
  • start = 10 (binary: 1010)
  • goal = 7 (binary: 0111)
  • start ^ goal = 1101 (4-bit number where 1s represent different bits).
  1. Counting 1s: Each 1 in the XOR result corresponds to a bit that needs to be flipped. By counting the number of 1s in the XOR result, we determine the number of bit flips needed to convert start to goal.

Time Complexity:

  • O(log N) where N is the maximum of start or goal. The time complexity is determined by the number of bits in the binary representation of the numbers.

Leave a Reply