Sponsored
Sponsored
The simplest way to determine the different bits between two numbers is to use the XOR operation. XORing two bits will yield 1 if the bits are different and 0 if they are the same. Thus, XORing two numbers will produce a number with bits set at positions where the input numbers have different bits. Counting the number of 1s in this result will give the number of flips required.
Time Complexity: O(n) where n is the number of bits in the maximum of the two numbers, as you may have to check each bit once.
Space Complexity: O(1) as no additional space is used.
1public class MinFlips {
2 public static int minFlips(int start, int goal) {
3 int xor = start ^ goal;
4 int count = 0;
5 while (xor != 0) {
6 count += xor & 1;
7 xor >>= 1;
8 }
9 return count;
10 }
11
12 public static void main(String[] args) {
13 int start = 10, goal = 7;
14 System.out.println(minFlips(start, goal)); // Output: 3
15 }
16}
The Java implementation follows a similar approach by using XOR to identify mismatched bits and counting those differing bits iteratively.
Many languages offer built-in functions to count the number of set bits (ones) in a binary number. Utilizing these handy functions can make our solution more concise and often more efficient. The bitwise XOR is computed between the two numbers, and the solution boils down to counting the number of set bits in the result.
Time Complexity: O(1) on systems where built-ins are optimized.
Space Complexity: O(1) since we use no additional resources.
Python makes it simple by converting the XOR result to a binary string and counting the '1's directly, a straightforward and efficient approach.