
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Counting the number of 1s upto n in JavaScript
We are required to write a JavaScript function that takes in a positive integer, say num.
The task of our function is to count the total number of 1s that appears in all the positive integers upto n (including n, if it contains any 1).
Then the function should finally return this count.
For example −
If the input number is −
const num = 31;
Then the output should be −
const output = 14;
because 1 appears in,
1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 21, 31
Example
Following is the code −
const num = 31; const countOnes = (num = 1) => { if(num <= 0 ){ return 0 }; let sum = 0 num += ''; let helper = p => { let leftNum = 0 let rightNum = 0 let di = num[p] if(p>0){ leftNum = parseInt(num.slice(0,p)) } if(p+1 < num.length){ rightNum = parseInt(num.slice(p+1)) } if(di > 1){ sum += (leftNum+1)*(10**(num.length-1-p)) } else if(di == 0){ sum += (leftNum)*(10**(num.length-1-p)) } else{ sum += (leftNum)*(10**(num.length-1-p)) + rightNum + 1 } } for(let i =0; i < num.length; i++){ helper(i) }; return sum; }; console.log(countOnes(num));
Output
Following is the console output −
14
- Related Questions & Answers
- Counting prime numbers from 2 upto the number n JavaScript
- Counting number of 9s encountered while counting up to n in JavaScript
- Prime numbers upto n - JavaScript
- Number of letters in the counting JavaScript
- Count number of 1s in the array after N moves in C
- Digit sum upto a number of digits of a number in JavaScript
- Counting divisors of a number using JavaScript
- Counting the number of redundant characters in a string - JavaScript
- Maximum consecutive 1s after n swaps in JavaScript
- Counting number of words in a sentence in JavaScript
- Sum all perfect cube values upto n using JavaScript
- Counting number of vowels in a string with JavaScript
- Listing all the prime numbers upto a specific number in JavaScript
- Find minimum number of Log value needed to calculate Log upto N in C++
- Counting number of triangle sides in an array in JavaScript
Advertisements