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.
1
This Python function leverages recursion to break down the number with each call, adapting functionality based on even or odd status, until zero is reached.