Counting the number of 1s upto n in JavaScript

JavascriptWeb DevelopmentFront End Technology

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
raja
Published on 27-Jan-2021 10:54:21
Advertisements