Minimum Bit Flips to Convert Number

A bit flip changes one bit of a number from 0 to 1 or from 1 to 0, including leading zeros you choose to write out. Given two integers start and goal, return the smallest number of bit flips that turns start into goal.

30:00

Minimum Bit Flips to Convert Number
easy
Free written solution
Topics
Companies

A bit flip changes one bit of a number from 0 to 1 or from 1 to 0, including leading zeros you choose to write out. Given two integers start and goal, return the smallest number of bit flips that turns start into goal.

Example 1:
Input: {"start":10,"goal":7}
Output: 3
Constraints:
  • 0≤start,goal≤1090 \leq \text{start}, \text{goal} \leq 10^9

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"start":10,"goal":7}

start = 1010 and goal = 111. Each bit can be flipped on its own, so the answer is the number of positions where they differ.

Where do start and goal disagree?

start
1
0
1
0
goal
0
1
1
1
3
2
1
0

diff & (diff - 1) drops the lowest 1

waits for the loop

start, flipped one bit per pass

flips = 0

now
1
0
1
0
goal
0
1
1
1
Variables
VariableValue
start10
goal7
DepthFunction Call
Stack empty
0/13