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.
1#include <iostream>
2class Solution {
3public:
4 int numberOfSteps(int num) {
5 int steps = 0;
6 while (num > 0) {
7 if (num % 2 == 0) {
8 num /= 2;
9 } else {
10 num -= 1;
11 }
12 steps++;
13 }
14 return steps;
15 }
16};
17int main() {
18 Solution s;
19 int num = 14;
20 std::cout << "Number of steps: " << s.numberOfSteps(num) << std::endl;
21 return 0;
22}
This C++ implementation uses a class with a method to perform the same iterative logic as described, ensuring the count of steps is returned and displayed correctly.
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
JavaScript's recursive approach utilizes a function that self-invokes while decrementing and division based on parity, cumulating steps until a zero base case is satisfied.