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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38334652/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:20:43  来源:igfitidea点击:

Sum all the digits of a number Javascript

javascriptnumberssumdigits

提问by Hodorogea Alexandru

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,应用程序将计算 2+5+6+8 等于 21。最后,它会计算 21 的数字之和,最终结果为 3 。

Please help me

请帮我

回答by Federico Antonucci

How about this simple approach using modulo 9 arithmetic?

这种使用模 9 算术的简单方法怎么样?

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

回答by Nina Scholz

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 valueproperty.

要返回值,您需要添加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"/>

回答by Konard

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. Because 2+5+6+8 = 21and 2+1 = 3.

sumDigitsRecursively(2568)表达将等于3。因为2+5+6+8 = 212+1 = 3

Note that recursive solutionby @FedericoAntonucci should be more efficient, but it does not give you intermediate sum of digits if you need it.

请注意,@FedericoAntonucci 的递归解决方案应该更有效,但如果您需要,它不会为您提供中间数字总和。