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.
1public class Solution {
2 public int 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 }
14 public static void main(String[] args) {
15 Solution solution = new Solution();
16 int num = 14;
17 System.out.println("Number of steps: " + solution.numberOfSteps(num));
18 }
19}
The solution follows the specified iterative logic within a method, counting steps, and makes use of a class to execute and print the results.
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.