Minimum One Bit Operations to Make Integers Zero

Hard · Bit Manipulation · Bit Manipulation · Recursion · Dynamic Programming · Memoization

Problem

You are given a non-negative integer n and must turn it into 0 with these two moves, used as often as you like:

Return the minimum number of moves needed to reach 0.

Examples

Input: n = 2
Output: 3

10 → 11 (move 1) → 01 (move 2, bit 0 is 1) → 00 (move 1): three moves.

Input: n = 5
Output: 6

101 → 111 → 110 → 010 → 011 → 001 → 000: six moves, and no shorter legal sequence exists.

Input: n = 0
Output: 0

Already zero.

Constraints

Approaches

Follow-up

The moves trace the reflected Gray code, so this is the Gray-code decode. Shifting by 1, 2, 4, 8 and 16 decodes a 32-bit number in five XORs. The use cases run the code forwards (the state after k moves) and measure the distance between two states.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…