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.
1function minFlips(start, goal) {
2 let xor = start ^ goal;
3 let count = 0;
4 while (xor !== 0) {
5 count += xor & 1;
6 xor >>= 1;
7 }
8 return count;
9}
10
11let start = 10, goal = 7;
12console.log(minFlips(start, goal)); // Output: 3
The JavaScript implementation sums the set bits in the XOR of two numbers to determine differing positions in their binary forms.
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.
This JavaScript code converts the XOR result to a binary string, splits on '1', and counts the elements, effectively counting the number of set bits.