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 <stdio.h>
2int numberOfSteps(int num) {
3 int steps = 0;
4 while (num > 0) {
5 if (num % 2 == 0) {
6 num /= 2;
7 } else {
8 num -= 1;
9 }
10 steps++;
11 }
12 return steps;
13}
14int main() {
15 int num = 14;
16 printf("Number of steps: %d", numberOfSteps(num));
17 return 0;
18}
The function numberOfSteps
iteratively checks if the number is even or odd, performs the respective operation, and increments the step counter until the number reduces to zero. The result is printed in the main function.
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
Java implementation relying on method recursion to resolve the problem by conditional operations on the number, with step information accumulated recursively.