You are given two integers start
and goal
. You want to convert start
to goal
using the minimum number of bit flips.
A bit flip is where you change a 0 to a 1 or a 1 to a 0.
Return the minimum number of bit flips to convert start
to goal
.
Example 1:
Input: start = 10, goal = 7
Output: 3
Explanation: The binary representation of 10 is 1010 and the binary representation of 7 is 0111. We need to flip all the bits at positions 0, 1, and 2.
Example 2:
Input: start = 3, goal = 4
Output: 3
Explanation: The binary representation of 3 is 011 and the binary representation of 4 is 100. We need to flip all the bits at positions 0, 1, and 2.
start
and goal
?
start
and goal
be negative?
To determine the minimum number of bit flips required to convert start
to goal
, we can use the following approach:
XOR Operation: Perform the XOR operation between start
and goal
. The XOR operation results in a bit being set to 1
if the bits differ, and 0
if they are the same.
Count Set Bits: Count the number of 1
s in the result of the XOR operation. This count will give the minimum number of bit flips needed to convert start
to goal
.
xor_result = start ^ goal
.1
bits in xor_result
.def minBitFlips(start: int, goal: int) -> int:
xor_result = start ^ goal
return bin(xor_result).count('1')
# Example usage
start = 10
goal = 7
print(minBitFlips(start, goal)) # Output: 3
start
and goal
. This is because in the worst case, we check all the bits of xor_result
, which is proportional to the number of bits required to represent n
.Feel free to run the example cases to see if the solution works as described. If there are any more specific constraints or edge cases to consider, please let me know!
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?