Leetcode 2220. Minimum Bit Flips to Convert Number
Given two integers start
and goal
, determine the minimum number of bit flips required to convert start
to goal
.
start
and goal
be negative numbers?
start
and goal
are non-negative integers.start
and goal
?
start
and goal
are within the range of 0 to 10^9.The problem can be solved using bit manipulation. Here’s the step-by-step strategy:
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.start
and goal
differ.start
to goal
.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;
}
b
is the number of bits in the binary representation of the maximum of start
and goal
. In this problem, b
is bounded by the maximum bit length of the given integers (log2(10^9) which is approximately 30), so it effectively runs in constant time.Feel free to ask if you have any further questions or need additional clarifications!
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?