A bit flip changes one bit in the binary representation of a number, either from 0 to 1 or from 1 to 0.
Given two integers start and goal, return the minimum number of bit flips needed to convert start to goal.
Function Signature
def min_bit_flips(start: int, goal: int) -> int:
Rules
-
Bit positions are counted from the least significant bit, starting at 0.
-
Both inputs are non-negative. Leading zeros may be flipped, and each such flip counts.
Constraints
Examples
Input: start = 10, goal = 7
Output: 3
In binary, 10 is 1010 and 7 is 0111. They differ at bit positions 0, 2 and 3, so three flips are needed.
Input: start = 3, goal = 4
Output: 3
3 is 011 and 4 is 100. All three bit positions differ, so 3 flips are needed.
Input: start = 1000000000, goal = 0
Output: 13
Since goal is 0, every set bit of start has to be cleared. 1,000,000,000 is 0x3B9ACA00, which has 13 set bits.