- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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 Gapful number in JavaScript
A number is gapful if it is at least 3 digits long and is divisible by the number formed by stringing the first and last numbers together. The smallest number that fits this description is 100. First digit is 1, last digit is 0, forming 10, which is a factor of 100. Therefore, 100 is gapful.
We are required to create a function that takes a number n and returns the closest gapful number (including itself). If there are 2 gapful numbers that are equidistant to n, return the lower one.
Some examples −
gapful(25) ➞ 100 gapful(100) ➞ 100 gapful(103) ➞ 105
Example
Following is the code −
const num = 4780; const isGapful = n => { if (n < 100){ return false; } const temp = Array.from(n.toString()); return n % (temp[0] + temp[temp.length - 1]) === 0; } function getClosestGapful(n) { let left = n, right = n; while (!isGapful(right)){ right++; } if (n < 100){ return right; } while (!isGapful(left)){ left++; } return n - left <= right - n ? left : right; }; console.log(getClosestGapful(25)); console.log(getClosestGapful(num));
Output
This will produce the following output on console −
100 4800
Advertisements