You are given a non-negative integer num
. Your task is to return the number of steps required to reduce num
to zero. In each step, if the current number is even, you must divide it by 2; if it is odd, you must subtract 1 from it. Repeat this process until the number becomes zero, and return the count of steps taken.
num
(0 ≤ num ≤ 106).num
to zero.At first glance, this problem seems straightforward: you simply follow the rules given, step by step, until you reach zero. The most direct way is to simulate the process:
The brute-force approach is to use a loop, repeatedly updating the number and incrementing a counter, until the number reaches zero. Since each operation either halves the number or decreases it by one, we can be confident this process will terminate quickly.
Before coding, you might wonder if there's a shortcut or mathematical formula. But since the rules are simple and the input range is moderate, simulating the process is both efficient and easy to understand. There’s no need for optimization beyond a basic loop.
Let's break down the solution step by step:
steps = 0
to count the number of operations.
num
until it becomes zero.
num
is even (num % 2 == 0
), divide by 2.num
is odd, subtract 1.num
reaches zero, return the step count.
This approach is efficient because each operation reduces the number quickly—either by halving (for even numbers) or by getting closer to an even number (for odd numbers).
Let's walk through the process with a sample input: num = 14
.
num = 14
, steps = 0.
So, the answer for num = 14
is 6 steps.
num
.
num
.
To solve the "Number of Steps to Reduce a Number to Zero" problem, we simply simulate the process of dividing by 2 for even numbers and subtracting 1 for odd numbers, counting each operation until we reach zero. This approach is both intuitive and efficient, with a time complexity of O(log n) and constant space usage. The elegance of the solution lies in its simplicity—by directly following the problem’s rules, we arrive at an optimal and readable solution.
class Solution:
def numberOfSteps(self, num: int) -> int:
steps = 0
while num != 0:
if num % 2 == 0:
num //= 2
else:
num -= 1
steps += 1
return steps
class Solution {
public:
int numberOfSteps(int num) {
int steps = 0;
while (num != 0) {
if (num % 2 == 0) {
num /= 2;
} else {
num -= 1;
}
steps++;
}
return steps;
}
};
class Solution {
public int numberOfSteps(int num) {
int steps = 0;
while (num != 0) {
if (num % 2 == 0) {
num /= 2;
} else {
num -= 1;
}
steps++;
}
return steps;
}
}
var numberOfSteps = function(num) {
let steps = 0;
while (num !== 0) {
if (num % 2 === 0) {
num = Math.floor(num / 2);
} else {
num -= 1;
}
steps++;
}
return steps;
};