
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 Closed Loops in a Number Using JavaScript
Other than all being a natural number, the numbers 0, 4, 6, 8, 9 have one more thing in common. All these numbers are formed by or contain at least one closed loop in their shapes.
For example, the number 0 is a closed loop, 8 contains two closed loops and 4, 6, 9 each contains one closed loop.
We are required to write a JavaScript function that takes in a number and returns the sum of the closed loops in all its digits.
For example, if the number is 4789
Then the output should be 4 i.e.
1 + 0 + 2 + 1
Example
Following is the code −
const num = 4789; const calculateClosedLoop = (num, { count, legend } = {count: 0, legend: {'0': 1, '4': 1, '6': 1, '8': 2, '9': 1}}) => { if(num){ return calculateClosedLoop(Math.floor(num / 10), { count: count + (legend[num % 10] || 0), legend }); }; return count; }; console.log(calculateClosedLoop(num));
Output
Following is the output in the console −
4
Advertisements