Minimum One Bit Operations to Make Integers Zero

Given an integer n, you must transform it into 0 using the following operations any number of times:

  • Change the rightmost (0^th) bit in the binary representation of n.
  • Change the i^th bit in the binary representation of n if the (i-1)^th bit is set to 1 and the (i-2)^th through 0^th bits are set to 0.

Return the minimum number of operations to transform n into 0.

Example 1
Inputn = 3
Output2
The binary representation of 3 is "11"; it can be transformed as "11" -> "01" -> "00" in 2 operations.
Example 2
Inputn = 6
Output4
The binary representation of 6 is "110"; it can be transformed as "110" -> "010" -> "011" -> "001" -> "000" in 4 operations.

Constraints

  • 0 <= n <= 10^9

Asked at 5 companies

Practice questions like this out loud in a mock coding interview with a live AI interviewer. First one free.

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, what to keep, what's wrong, and the complexity of your solution.

Sign in to evaluate