Bring number down to 1 in JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in number, num as the only argument.

  • Our function can do only these two operations on num: If num is even, we can replace num with num/2

  • If num is odd, we can replace num with either num + 1 or num - 1.

Using only a combination of these two operations our function is required to compute how many minimum operations it requires to bring num down to 1. The function should return the minimum number of operations.

For example, if the input to the function is −

const num = 7;

Then the output should be −

const output = 4;

Output Explanation:

Because the smallest possible operations are −

7 -> 8 -> 4 -> 2 -> 1
or
7 -> 6 -> 3 -> 2 -> 1

Example

The code for this will be −

 Live Demo

const num = 7;
const downToOne = (num = 1) => {
   let min = Number.POSITIVE_INFINITY;
   let stack = [{ num: num, step: 0 }];
   let set = new Set();
   let next;
   let item;
   while (stack.length) {
      item = stack.shift();
      if (item.num === 1) {
         if (min > item.step) {
            min = item.step;
         }
         continue;
      }
      if (set.has(item.num) || item.step >= min) {
         continue;
      }
      set.add(item.num);
      next = item.step + 1;
      if (item.num % 2 === 0) {
         item.num /= 2;
         stack.push({ num: item.num, step: next });
      } else {
         stack.push({ num: item.num - 1, step: next });
         stack.push({ num: item.num + 1, step: next });
      }
   }
   return min;
};
console.log(downToOne(num));

Output

The output in the console will be −

4
raja
Published on 18-Mar-2021 13:29:01
Advertisements