Skip to content

Edvins Antonovs

Number of steps to reduce a number to zero code challenge

My approach to solving LeetCode’s Number of steps to reduce a number to zero code challenge.


Problem

Given an integer num, return the number of steps to reduce it to zero.

In one step, if the current number is even, you have to divide it by 2, otherwise, you have to subtract 1 from it.

Example

1Input: num = 14
2Output: 6
3Explanation:
4Step 1) 14 is even; divide by 2 and obtain 7.
5Step 2) 7 is odd; subtract 1 and obtain 6.
6Step 3) 6 is even; divide by 2 and obtain 3.
7Step 4) 3 is odd; subtract 1 and obtain 2.
8Step 5) 2 is even; divide by 2 and obtain 1.
9Step 6) 1 is odd; subtract 1 and obtain 0.

Solution

In this given solution, I'm mutating the initial num as it gave me an overall better performance (runtime speed and memory usage).

We begin with null checking. We return null if the initially given number (num) is zero. Then we create steps variables which will hold the number of steps we took.

Then we run a while loop until the given value is zero. We check if the number is even (num % 2); if it is, we divide it by 2; else, we subtract -1 from it. During each loop, we bump the number of steps by 1.

Then we return the steps value.

1const numberOfSteps = (num) => {
2 if (num === 0) return 0;
3
4 let steps = 0;
5
6 while (num !== 0) {
7 if (num % 2 === 0) {
8 num = num / 2;
9 } else {
10 num--;
11 }
12
13 steps++;
14 }
15
16 return steps;
17};
© 2024 by Edvins Antonovs. All rights reserved.