Minimum Bit Flips to Convert Number

easy

A bit flip turns a single bit of a number's binary form 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 into goal.

Hints

Which bit positions actually force you to do something?
A position only needs a flip when start and goal disagree there.
XOR hands you exactly the disagreeing bits — now just count them.

Common doubts

No. Positions where both numbers are 0 (including leading zeros) never need a flip, so they add nothing to the count.
Yes. The minimum number of bit flips between two numbers is exactly the Hamming distance between their binary representations.

Interview follow-ups

Compare columnwise — for each bit position, count how many numbers have a 1 — or sum pairwise popcounts. Same XOR-and-count idea, applied across the set.
Nothing changes conceptually — use a 64-bit type and the same XOR-then-count (or a built-in popcount).

Fun facts

  • Clearing the lowest set bit with x & (x - 1) is known as Brian Kernighan's algorithm.
  • This exact 'count the differing bits' operation is how error-correcting codes measure how far apart two codewords are.

Asked at

AmazonGoogleMicrosoft
Frequently Sometimes Occasionally
Example 1
Input: start = 10, goal = 7
Output: 3
10 is 1010 and 7 is 0111 in binary; they differ in 3 bit positions.
Example 2
Input: start = 3, goal = 4
Output: 3
3 is 011 and 4 is 100 in binary; they differ in 3 bit positions.
Constraints

- 0 <= start, goal <= 10^9

Solve this problem →