Show problems as
Classic problem #2220EasyBit Manipulation

Minimum Bit Flips to Convert Number

Real-world version: Throws Between Two Switch Banks
Tracked in this browser only
Read Minimum Bit Flips to Convert Number on LeetCode(opens in a new tab)

The 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.

Python
def min_bit_flips(start: int, goal: int) -> int:
Java
public int minBitFlips(int start, int goal)