Home  >  Article  >  Web Front-end  >  2 Keyboard issues in JavaScript

2 Keyboard issues in JavaScript

王林
王林forward
2023-08-24 08:45:02518browse

2 JavaScript 中的键盘问题

Assume the following situation -

Initially, there is only one character "A" on the notepad. We can perform two actions on this notepad for each step -

  • Copy All - We can copy all characters on the notepad (partial copying is not allowed).

  • Paste - We can paste the last copied characters.

We need to write a JavaScript function which accepts a number, let's call it num as the only parameter. Our function needs to calculate and return the minimum number of steps required to print "A" times (copy all or paste).

For example -

If the input number is -

const num = 3;

then the output should be -

const output = 3;

because, the steps are -

  • Copy all (result: 'A')

  • Paste all (result: 'AA')

  • Paste all ( Result: 'AAA')

Example h2>

its code is-

Live Demo

const num = 3;
const minimumSteps = (num = 1) => {
   let [curr, copy, steps] = [1, 0, 0];
   while(curr != num){
      if((copy < curr) && ((num - curr) % curr) == 0) {
         copy = curr;
      }else{
         curr += copy;
      };
      steps += 1;
   };
   return steps;
};
console.log(minimumSteps(num));

Output

The output in the console will be -

3

The above is the detailed content of 2 Keyboard issues in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete