Home > Web Front-end > JS Tutorial > body text

2 Keyboard issues in JavaScript

王林
Release: 2023-08-24 08:45:02
forward
502 people have browsed it

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;
Copy after login

then the output should be -

const output = 3;
Copy after login

because, the steps are -

  • Copy all (result: 'A')

  • Paste all (result: 'AA')

  • Paste all ( Result: 'AAA')

Example

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));
Copy after login

Output

The output in the console will be -

3
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!