Ctrl K

Guarded Bit Flips Down to Zero

Hard
You get a non-negative integer value. Turn it into 0 by flipping one bit of its binary form per step. Only two kinds of steps are allowed: - flip the lowest bit (bit 0), which is always allowed; - flip bit i (for i ≥ 1), but only when bit i - 1 is 1 and every bit below it (i - 2, ..., 0) is 0. Return the smallest number of steps.
Example 1
value=2 → 3

10 → 11 (the lowest bit can always be flipped) → 01 (bit 1 may flip because bit 0 is 1) → 00. Three steps.

Example 2
value=5 → 6

The shortest route is 101 → 111 → 110 → 010 → 011 → 001 → 000, which is 6 steps.

Example 3
value=0 → 0
Constraints
  • 0 ≤ value ≤ 10⁹
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsQuiet and Sociable Tenants HardFresh Trays for Every Party HardHarvesting a Tree: Toll or Half HardGrasshopper on an Endless Staircase HardSteps Down to One Medium
loading Python…
Input
value=2
Expected
3

Run checks the first 3 tests in your browser. Submit checks all 71 tests on the server, hidden ones included.