Leetcode 2220. Minimum Bit Flips to Convert Number
You are given two integers start and goal. The task is to determine the minimum number of bit flips required to convert start to goal.
0 <= start, goal <= 10^9start and goal be the same?
start XOR goal will give a number where each bit is 1 if the corresponding bits of start and goal differ.public class MinimumBitFlips {
public static int minBitFlips(int start, int goal) {
// XOR operation to find differing bits
int xorResult = start ^ goal;
// Count the number of 1's in the XOR result
int count = 0;
while (xorResult != 0) {
count += xorResult & 1;
xorResult >>= 1;
}
return count;
}
public static void main(String[] args) {
// Sample run
int start = 10; // Binary: 1010
int goal = 20; // Binary: 10100
System.out.println(minBitFlips(start, goal)); // Output should be 4 (since 1010 -> 10100)
}
}
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?