简体   繁体   中英

JavaScript | Sum of number of digits issue

I was solving one puzzle on counting no of digits in a number. Below is the code:

 function countDigits(n) {
 console.log(n);
 let count = 0;
 while (n > 0) {
     let d = n % 10;
     count += d;
     n = Math.floor(n / 10);
 }
 return count; }

Most of the text cases gets passed except when no. Of digits in input exceeds 17.

Test Case:

  • n = 3546630947312051453014172159647935984478824945973141333062252613718025688716704470547449723886626736

    Expected: 446

    Getting: 380

  • n = 35466309473120515

    Expected: 64

    Getting: 65

After going through some posts online, I came to know that JavaScript will truncate values if number exceeds 17 digits, for an instance:

var a = 35466309473120515
console.log(a) // a => 35466309473120516

To resolve this issue in their API Twitter sends tweed id in string instead of number. More details here .

But in my case I don't have any control over input value. If value exceeds input range (>17), as I convert it to string.

Kindly let me know how can I resolve this.

numbers in javascript are stored on 64 bits : 53 bits for integer value + 11 bits for mantissa:

Hence, Number.MAX_SAFE_INTEGER === 9007199254740991 is the greatest integer you can use without loss of precision.

if your input value is a string, you could simply

  1. check it contains only digits with a regex

  2. get length of your string

edit: post title is counting number of digits but your code is actually summing the number of digits. What do you actually want ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM