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.
1using System;
2class Solution {
3 public int NumberOfSteps(int num) {
4 int steps = 0;
5 while (num > 0) {
6 if (num % 2 == 0) {
7 num /= 2;
8 } else {
9 num -= 1;
10 }
11 steps++;
12 }
13 return steps;
14 }
15 static void Main() {
16 Solution s = new Solution();
17 int num = 14;
18 Console.WriteLine("Number of steps: " + s.NumberOfSteps(num));
19 }
20}
A class-based solution in C# performing the iterative reduction of the number with a simple loop, counting steps efficiently.
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.