
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
Finding Least Number of Notes to Sum an Amount in JavaScript
Suppose, we have a currency system where we have denominations of 1000 units, 500 units, 100 units, 50 units, 20 units, 10 units, 5 units, 2 units and 1 unit.
Given a specific amount, we are required to write a function that calculates the least number of total denominations that sum up to the amount.
For example, if the amount is 512,
The least number of notes that will add up to it will be: 1 unit of 500, 1 unit of 10 and 1 unit of 2.
So, in this we for 512, our function should return 3, i.e., the total count of notes
Let’s write the code for this function −
Following is the code −
const sum = 512; const countNotes = sum => { let count = 0; while(sum){ if(sum >= 1000){ sum -= 1000; count++; continue; }else if(sum >= 500){ sum -= 500; count++; continue; }else if(sum >= 100){ sum -= 100; count++; continue; }else if(sum >= 50){ sum -= 50; count++; continue; }else if(sum >= 20){ sum -= 20; count++; continue; }else if(sum >= 10){ sum -= 10; count++; continue; }else if(sum >= 5){ sum -= 5; count++; continue; }else if(sum >= 2){ sum -= 2; count++; continue; }else{ sum -= 1; count++; continue; } }; return count; }; console.log(countNotes(sum));
Output
Following is the output in the console −
3
Advertisements