Problem
Given an integer num, return the number of steps to reduce it to zero.
In one step, if the current number is even, you have to divide it by 2, otherwise, you have to subtract 1 from it.
Examples
Example 1:
|
|
Example 2:
|
|
Solution
Method 1 - With Right Shift Operator
- We keep on dividing the number by 2, but we have to check if number is odd or even.
- Process the binary number from right to left and check if:
- Encountering a 0 (even number): divide by 2 increases
resultby 1 (result += 1) - Encountering a 1 (odd number): increases result by 2, (
result += 2). The reason is 1 operation for subtracting, and now it becomes even, so we divide again. Hence 2 operations. - only exception is the leftmost 1, because now number is 1, and we treat it is as odd. So, we do result+=2, but actually it just increase result by 1. So, we just do a “-1” and number becomes 0 already.
- Encountering a 0 (even number): divide by 2 increases
Code
|
|
Method 2 - Without Bit Manipulation
Code
|
|