简体   繁体   English

数字javascript的数字之和

[英]sum of the digits of a number javascript

I saw a bunch of other posts on this topic but none in javascript. 我在这个主题上看到了很多其他帖子,但在javascript中没有。 here is my code. 这是我的代码。

var theNumber = function digitAdd (base, exponent) {
    var number = 1;
    for (i=0; i < exponent; i++) {
        var number = base * number;
    }
    return number
}


function find(theNumber) {
 var sum=0;
    parseInt(theNumber);
    while(theNumber>0)
     {
       sum=sum+theNumber%10;
       theNumber=Math.floor(theNumber/10);
      }
    document.writeln("Sum of digits  "+sum);
   }

find(theNumber (2, 50));

I am getting the correct answer, I just don't fully understand the 2nd function, namely the while statement. 我得到了正确的答案,我只是不完全理解第二个函数,即while语句。 Any help would be greatly appreciated. 任何帮助将不胜感激。 Thanks! 谢谢!

The second function uses the modulo operator to extract the last digit: 第二个函数使用模运算符来提取最后一个数字:

  1236 % 10
= 1236 - 10 * floor(1236 / 10)
= 1236 - 1230
= 6

When the last digit is extracted, it is subtracted from the number: 提取最后一位数字时,从数字中减去它:

  1236 - 6
= 1230

And the number is divided by 10 : 数字除以10

  1230 / 10
= 123

Each time this loop repeats, the last digit is chopped off and added to the sum. 每次重复此循环时,最后一位数字将被切断并添加到总和中。

The modulo operator returns the single digit if the left hand side is smaller than the right (which will happen for any 1-digit number), which is when the loop breaks: 如果左侧小于右侧(对于任何1位数字将发生),模运算符返回单个数字,这是循环中断时:

  1 % 10
= 1

This is how the leading digit gets added to the total. 这是将前导数字添加到总数中的方式。


A less numeric alternative would be this: 一个较少数字的替代方案是:

function sumDigits(number) {
  var str = number.toString();
  var sum = 0;

  for (var i = 0; i < str.length; i++) {
    sum += parseInt(str.charAt(i), 10);
  }

  return sum;
}

It does literally what you are trying to do, which is iterate over the digits of the number (by converting it to a string). 它确实是你要做的事情,它迭代数字的数字(通过将其转换为字符串)。

i use it :) 我用它 :)

 var result = eval('123456'.replace(/(\\d)(?=\\d)/g, '$1+')); alert(result); // 21 

without eval 没有评估

 var result = '123456'.split('').reduce(function(a,b){ return +a+ +b; }); alert(result); // 21 

i use this : 我用这个:

'123456'.split('').map(function(e){return parseInt(e)}).reduce(function(a,b){return a+b}); //21

Update (ES6 syntax) : 更新(ES6语法):

[...'123456'].map(e=>parseInt(e)).reduce((a,b)=>a+b); //21

Not sure what you meant, In case you were asking about while loop.. 不确定你的意思,如果你问的是while循环..

The while statement continually executes a block of statements while a particular condition is true. while语句在特定条件为真时继续执行语句块。 Its syntax can be expressed as: 其语法可表示为:

while (expression) {
     statement(s)
}

The while statement evaluates expression, which must return a boolean value. while语句计算表达式,该表达式必须返回一个布尔值。 If the expression evaluates to true, the while statement executes the statement(s) in the while block. 如果表达式的计算结果为true,则while语句将执行while块中的语句。 The while statement continues testing the expression and executing its block until the expression evaluates to false. while语句继续测试表达式并执行其块,直到表达式求值为false。

The while loop here is extracting digits one by one from the actual number and adding those. 这里的while循环是从实际数字中逐个提取数字并添加它们。 Try to do each step manually and you will get it. 尝试手动完成每一步,你就会得到它。

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

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