# 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

`.css-l84w3r{background-color:rgba(107,70,193,0.2);border:none;color:var(--theme-ui-colors-gray-2,#edf2f7);cursor:pointer;font-size:14px;font-family:"IBM Plex Sans",-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,"Noto Sans",sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";-webkit-letter-spacing:0.025rem;-moz-letter-spacing:0.025rem;-ms-letter-spacing:0.025rem;letter-spacing:0.025rem;-webkit-transition:default;transition:default;position:absolute;top:0;right:0;z-index:1;border-radius:0 0 0 0.25rem;padding:0.25rem 0.6rem;}@media screen and (min-width:640px){.css-l84w3r{font-size:14px;}}@media screen and (min-width:768px){.css-l84w3r{font-size:16px;}}.css-l84w3r[disabled]{cursor:not-allowed;}.css-l84w3r:not([disabled]):hover{background-color:var(--theme-ui-colors-primary,#6b46c1);color:var(--theme-ui-colors-white,#fff);}`1Input: num = 142Output: 63Explanation: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};``````