algoadvance

Leetcode 2220. Minimum Bit Flips to Convert Number

Problem Statement

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

Clarifying Questions

  1. Q: Can start and goal be negative numbers?
    • A: No, both start and goal are non-negative integers.
  2. Q: What is the range of start and goal?
    • A: Both start and goal are within the range of 0 to 10^9.
  3. Q: Do I need to consider the binary representation size?
    • A: No, standard integer handling and binary manipulation are sufficient for this problem.

Strategy

The problem can be solved using bit manipulation. Here’s the step-by-step strategy:

  1. XOR Operation: Using XOR (exclusive OR), compare start and goal. The XOR operation between two bits results in 1 if the bits are different and 0 if they are the same. Thus, start XOR goal will give us a number whose binary representation has bits set to 1 wherever start and goal differ.
  2. Count Set Bits: Count the number of set bits (1s) in the result from the XOR operation. Each set bit represents a position where the bits of start and goal differ.
  3. Result: The count of set bits is the minimum number of bit flips required to convert start to goal.

Code

Here is the implementation of the above strategy in C++:

#include <iostream>

int minBitFlips(int start, int goal) {
    // XOR start and goal to find differing bits
    int xorResult = start ^ goal;
    
    // Count the number of set bits in xorResult
    int count = 0;
    while (xorResult > 0) {
        count += xorResult & 1;  // Increment count if the least significant bit is 1
        xorResult >>= 1;         // Right shift to process the next bit
    }
    return count;
}

int main() {
    int start = 10;  // Example input
    int goal = 7;    // Example input
    
    std::cout << "Minimum bit flips required: " << minBitFlips(start, goal) << std::endl;
    return 0;
}

Time Complexity

Feel free to ask if you have any further questions or need additional clarifications!

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI