Sponsored
Sponsored
In this approach, we use a loop to repetitively apply the given conditions on the number. If the number is even, divide it by 2, and if odd, subtract 1. We count and return the number of operations needed to reduce the number to zero.
Time Complexity: O(log n) where n is the initial number.
Space Complexity: O(1), since no additional space is used.
1function numberOfSteps(num) {
2 let steps = 0;
3 while (num > 0) {
4 if (num % 2 === 0) {
5 num /= 2;
6 } else {
7 num -= 1;
8 }
9 steps++;
10 }
11 return steps;
12}
13
14let num = 14;
15console.log('Number of steps:', numberOfSteps(num));
The JavaScript function numberOfSteps
executes the logic of checking and modifying the number iteratively using a loop, similar to the above languages.
This approach uses recursion to handle the problem. The function calls itself with the same logical conditions: divide by 2 for even or subtract 1 for odd, until the base case of zero is reached. It accumulates the count of steps through recursive calls.
Time Complexity: O(log n)
Space Complexity: O(log n), considering function call stack for recursion.
1class Solution {
public:
int numberOfSteps(int num) {
if (num == 0) return 0;
return 1 + numberOfSteps(num % 2 == 0 ? num / 2 : num - 1);
}
};
int main() {
Solution s;
int num = 14;
std::cout << "Number of steps: " << s.numberOfSteps(num) << std::endl;
return 0;
}
Implemented with a class in C++, where the primary method recursively breaks down the number according to its parity until zero is achieved.