← DiffPush

Minimum bit flips

Baseline Bit Manipulation · Interview Problems O(log n) — one pass over the differing bits (fixed 32 in the source) · O(1)

Re-Programming the Robot's Mode Register

A warehouse robot's mode register must change from its current setting to a goal setting, and each reprogramming run flips exactly one bit. The maintenance log wants the minimum number of flip runs. XOR-ing the two registers leaves a 1 in every position that disagrees, so the answer is simply how many 1s survive that comparison.

Input: Two integers start and goal.

Output: The minimum number of bit flips to turn start into goal.

Constraints

Examples

Example 1

Input: {"start":10,"goal":7}
Output: 3
1010 vs 0111 differ in three positions, so three flips are both necessary and sufficient.

Example 2

Input: {"start":3,"goal":4}
Output: 3
011 vs 100 disagree everywhere — every bit must be flipped.

Solve this in your browser →

Also on LeetCode ↗