简体   繁体   English

对一个数的所有数字求和 Javascript

[英]Sum all the digits of a number Javascript

I am newbie.我是新手。

I want to make small app which will calculate the sum of all the digits of a number.我想制作一个小应用程序来计算一个数字的所有数字的总和。

For example, if I have the number 2568, the app will calculate 2+5+6+8 which is equal with 21. Finally, it will calculate the sum of 21's digits and the final result will be 3.比如我有2568这个数,app会计算2+5+6+8等于21,最后会计算21位数字的和,最后的结果就是3。

Please help me请帮我

Basically you have two methods to get the sum of all parts of an integer number.基本上你有两种方法来获得一个整数的所有部分的总和。

  • With numerical operations用数值运算

    Take the number and build the remainder of ten and add that.取数字并建立十的余数并将其相加。 Then take the integer part of the division of the number by 10. Proceed.然后取数字除以 10 的整数部分。继续。

 var value = 2568, sum = 0; while (value) { sum += value % 10; value = Math.floor(value / 10); } console.log(sum);

  • Use string operations使用字符串操作

    Convert the number to string, split the string and get an array with all digits and perform a reduce for every part and return the sum.将数字转换为字符串,拆分字符串并获得一个包含所有数字的数组,并对每个部分执行归约并返回总和。

 var value = 2568, sum = value .toString() .split('') .map(Number) .reduce(function (a, b) { return a + b; }, 0); console.log(sum);


For returning the value, you need to addres the value property.要返回值,您需要添加value属性。

rezultat.value = sum;
//      ^^^^^^

 function sumDigits() { var value = document.getElementById("thenumber").value, sum = 0; while (value) { sum += value % 10; value = Math.floor(value / 10); } var rezultat = document.getElementById("result"); rezultat.value = sum; }
 <input type="text" placeholder="number" id="thenumber"/><br/><br/> <button onclick="sumDigits()">Calculate</button><br/><br/> <input type="text" readonly="true" placeholder="the result" id="result"/>

How about this simple approach using modulo 9 arithmetic?这种使用模 9 算术的简单方法怎么样?

function sumDigits(n) {
  return (n - 1) % 9 + 1;
}

If we wants to calculate the sum of digits for a value. 如果我们要计算一个值的数字总和。

 var value=2568; while(value > 9){ value=sum(value); } console.log(value) function sum(value){ var sum=value.toString().split("") .reduce(function(a,b) { return a+parseInt(b); },0); return sum; } 

With mathy formula:用数学公式:

function sumDigits(n) { 
    return (--n % 9) + 1;
}

Without mathy formula:没有数学公式:

function sumDigits(n) {
    if (typeof n !== 'string') {
        n = n.toString();
    }    
    if (n.length < 2) {
        return parseInt(n);
    }
​
    return sumDigits(
        n.split('')
         .reduce((acc, num) => acc += parseInt(num), 0)
    );
}

You could do it this way.你可以这样做。

function sums(input) {
    let numArr = input.toString().split('');
    let sum = numArr.reduce((a, b) => Number(a) + Number(b));
    return sum < 10 ? sum : sums(sum);
}
var value = -2568;
console.log(Math.abs(value % 9));

Answer is 3 答案是3

This is how I have solved this : 这就是我解决这个问题的方法:

function sumOfDigits(number) {    
    Math.abs(number).toString().split('').reduce(function(a,b){return +a + +b}, 0);
}

this will return 这将返回

sumOfDigits(10);  // Returns 1
sumOfDigits(-32); // Returns 5

If the value is greater than 10 then loop the funcrion 如果该值大于10,则循环该函数

let's try recursivity让我们试试递归

function sumDigits(n) {
  if (n < 10) return n
  return sumDigits(n % 10 + sumDigits(Math.floor(n / 10)))
}

sumDigits(2) // 2
sumDigits(2568) // 3

Below is a solution which will handle even NaN scenario too. 下面是一个甚至可以处理NaN方案的解决方案。

 function add(num) { var sum = 0; do { sum = sum + num%10; num = Math.floor(num/10); } while (num); return sum; } console.log(add())//NaN console.log(add(1234))//10 

do... while loop will be better for this problem rather than while loop. do ... while循环比while循环更适合于此问题。

According to For example, if I have the number 55555, the app will calculate 5+5+5+5+5 which is equal with 25. Finally, it will calculate the sum of 25 digits and the final result will be 7. 例如,根据我的数字55555,应用程序将计算5 + 5 + 5 + 5 + 5(等于25)。最后,它将计算25位数字的总和,最终结果将为7。

let value =55555; // => 25 => 7
function sumOfEachDigits(number) {    
    return Math.abs(number).toString().split('').reduce(function(a,b){return +a + +b}, 0);
}
while(value > 9){
    value=sumOfEachDigits(value);
}
console.log(value); // Result is 9

给出了一个更早的答案,重写为一个函数var value = 2568 function sumDigits(boo){return boo .toString().split('').map(Number).reduce(function(j,k){return j + k;})} sumDigits(value);

The sum of digits can be calculated using that function (based on other answers):可以使用该函数计算数字总和(基于其他答案):

function sumDigits(n) {
    let sum = 0;
    while (n) {
        digit = n % 10;
        sum += digit;
        n = (n - digit) / 10;
    }
    return sum;
}

If you really need to sum the digits recursively there is recursive version of the function:如果您确实需要递归地求和数字,则可以使用该函数的递归版本:

function sumDigitsRecursively(n) {
    let sum = sumDigits(n);
    if (sum < 10)
        return sum;
    else
        return sumDigitsRecursively(sum);
}

The sumDigitsRecursively(2568) expression will be equal to 3 . sumDigitsRecursively(2568)表达式将等于3 Because 2+5+6+8 = 21 and 2+1 = 3 .因为2+5+6+8 = 212+1 = 3

Note that recursive solution by @FedericoAntonucci should be more efficient, but it does not give you intermediate sum of digits if you need it.请注意,@FedericoAntonucci 的递归解决方案应该更有效,但如果您需要,它不会为您提供中间数字总和。

Expanding upon @fethe 's answer, this sumOfDigit function is able to handle large number or BigInt扩展@fethe 的答案,这个sumOfDigit函数能够处理大数或BigInt

function sumOfDigits(n) { 
  return (Number.isSafeInteger(n)) ? (--n % 9) + 1 : Number((--n % 9n) + 1n);
}

console.log(sumOfDigits(101)); // 2
console.log(sumOfDigits(84932)); // 8
console.log(sumOfDigits(900000000000000000000000009n)); // 9

you can use this function and pass your number to it:你可以使用这个 function 并将你的号码传递给它:

const solution = (n) => {
    const arr = `${n}`
    let sum = 0;
    for (let index = 0; index < arr.length; index++) {
        sum += parseInt(arr[index])
    }
    return sum;
}

 var value = 2568, sum = 0; while (value) { sum += value % 10; value = Math.floor(value / 10); } console.log(sum); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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