Count the bit flips needed to turn one integer into another

Quick Overview

Given two non-negative integers, find the minimum number of single-bit flips that turn the first into the second. It is a short bit manipulation exercise that tests how well you reason about binary representations and bitwise operators.

Count the bit flips needed to turn one integer into another

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: easy

Interview Round: Other

A bit flip changes one bit in the binary representation of a number, either 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` to `goal`. ### Function Signature ```python def min_bit_flips(start: int, goal: int) -> int: ``` ### Rules - Bit positions are counted from the least significant bit, starting at 0. - Both inputs are non-negative. Leading zeros may be flipped, and each such flip counts. ### Constraints - `0 <= start, goal <= 10^9` ### Examples ```text Input: start = 10, goal = 7 Output: 3 ``` In binary, 10 is `1010` and 7 is `0111`. They differ at bit positions 0, 2 and 3, so three flips are needed. ```text Input: start = 3, goal = 4 Output: 3 ``` 3 is `011` and 4 is `100`. All three bit positions differ, so 3 flips are needed. ```text Input: start = 1000000000, goal = 0 Output: 13 ``` Since `goal` is 0, every set bit of `start` has to be cleared. 1,000,000,000 is `0x3B9ACA00`, which has 13 set bits.

Overview: Given two non-negative integers, find the minimum number of single-bit flips that turn the first into the second. It is a short bit manipulation exercise that tests how well you reason about binary representations and bitwise operators.

PracHub logo
General
Nov 25, 2026
easySoftware EngineerOtherCoding & Algorithms
0
0

A bit flip changes one bit in the binary representation of a number, either 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 to goal.

Function Signature

def min_bit_flips(start: int, goal: int) -> int:

Rules

  • Bit positions are counted from the least significant bit, starting at 0.
  • Both inputs are non-negative. Leading zeros may be flipped, and each such flip counts.

Constraints

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

Examples

Input: start = 10, goal = 7
Output: 3

In binary, 10 is 1010 and 7 is 0111. They differ at bit positions 0, 2 and 3, so three flips are needed.

Input: start = 3, goal = 4
Output: 3

3 is 011 and 4 is 100. All three bit positions differ, so 3 flips are needed.

Input: start = 1000000000, goal = 0
Output: 13

Since goal is 0, every set bit of start has to be cleared. 1,000,000,000 is 0x3B9ACA00, which has 13 set bits.