Problem 851
Number of Steps to Reduce a Number to Zero
Easy · 10 pts · Math, Bit Manipulation
Problem
Start with a non-negative integer N. In one step, if the number is even divide it by 2, otherwise subtract 1. Count the steps needed to reach 0. A simulation takes O(log N) steps. In binary, every 1 bit costs one subtraction and every bit except the leading one costs one halving, so the count is (number of 1 bits) + (number of bits) - 1 for N > 0.
Input
A single integer N.
Output
Print the number of steps to reach 0.
Constraints
0 <= N <= 10^9
Example input
14
Example output
6
Explanation
14 → 7 (halve) → 6 (subtract) → 3 (halve) → 2 (subtract) → 1 (halve) → 0 (subtract). That is 6 steps.