
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
2-Key Keyboard Problem in JavaScript
Suppose the following situation −
Initially on a notepad only one character 'A' is present. We can perform two operations on this notepad for each step −
Copy All − We can copy all the characters present on the notepad (partial copy is not allowed).
Paste − We can paste the characters which were copied last time.
We are required to write a JavaScript function that takes in a number, let's call it num as the only argument. Our function is required to compute and return the minimum number of steps (copy all or paste) required to print 'A' num times.
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
The code for this will be −
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
And the output in the console will be −
3