Minimum Number of One Bit Operations to Make Integers Zero

Hard Topics Company Tags

Transform the nonnegative integer n into 0 by flipping bits. Bit positions start at 0 for the least significant bit. Each operation may do one of the following:

  • Flip bit 0.
  • Flip bit i > 0 if bit i - 1 is 1 and all bits below it are 0. For i = 1, there are no lower bits to check.

Return the minimum number of operations required.

Example 1:

Input: n = 0

Output: 0

Explanation: The value is already zero, so no operation is needed.

Example 2:

Input: n = 1

Output: 1

Explanation: Flip bit 0 to change binary 1 into 0 in one operation.

Example 3:

Input: n = 2

Output: 3

Explanation: A shortest sequence in binary is 10 -> 11 -> 01 -> 00. The middle step flips bit 1 while bit 0 is 1; the other two steps flip bit 0.

Constraints:

  • 0 <= n <= 1000000000


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.