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:
Input:
num = 14
Output:
6
Explanation:
Step 1) 14 is even; divide by 2 and obtain 7.
Step 2) 7 is odd; subtract 1 and obtain 6.
Step 3) 6 is even; divide by 2 and obtain 3.
Step 4) 3 is odd; subtract 1 and obtain 2.
Step 5) 2 is even; divide by 2 and obtain 1.
Step 6) 1 is odd; subtract 1 and obtain 0.
Example 2:
Input:
num = 8
Output:
4
Explanation:
Step 1) 8 is even; divide by 2 and obtain 4.
Step 2) 4 is even; divide by 2 and obtain 2.
Step 3) 2 is even; divide by 2 and obtain 1.
Step 4) 1 is odd; subtract 1 and obtain 0.
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
result
by 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
Java
public int numberOfSteps (int num) {
if (num == 0) {
return 0;
}
int ans = 0;
while (num != 0) {
ans += (num & 1) == 0 ? 1 : 2;
num >>= 1;
}
return ans - 1;
}
Method 2 - Without Bit Manipulation
Code
Java
public int numberOfSteps(int num) {
int ans = 0;
while (num > 0) {
if (num % 2 == 0) {
num /= 2;
} else {
num--;
}
ans++;
}
return ans;
}