Minimum Bit Flips to Convert Number
Real-world version: Throws Between Two Switch BanksThe statement here is our own: the same inputs, outputs and technique.
Two banks of switches are described by the whole numbers start and goal. A switch is on wherever the number carries a 1 bit, switches are numbered from the lowest bit upwards, and any place beyond a number's own bits counts as off.
One throw flips a single switch. Return the fewest throws that turn the start bank into the goal bank.
Examples
Example 1
- Input
- start = 15, goal = 240
- Output
- 8
The lowest four switches are on in the first bank and off in the second, and the next four are the other way round, so all eight have to be thrown.
Example 2
- Input
- start = 1023, goal = 1024
- Output
- 11
The first bank has its lowest ten switches on while the second has only the eleventh, so ten switches go off and one comes on.
Example 3
- Input
- start = 1, goal = 1
- Output
- 0
The two banks already match, so nothing is thrown.
Constraints
- 0 <= start <= 10^9
- 0 <= goal <= 10^9
The signature
The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def min_bit_flips(start: int, goal: int) -> int:public int minBitFlips(int start, int goal)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 15 test cases: 15 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's