一个数字的数字之和javascript

sum of the digits of a number javascript(一个数字的数字之和javascript)

本文介绍了一个数字的数字之和javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到了很多关于这个主题的其他帖子,但没有一个是在 javascript 中的.这是我的代码.

I saw a bunch of other posts on this topic but none in 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));

我得到了正确答案,我只是不完全理解第二个函数,即 while 语句.任何帮助将不胜感激.谢谢!

I am getting the correct answer, I just don't fully understand the 2nd function, namely the while statement. 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

而数字除以10:

  1230 / 10
= 123

每次循环重复时,最后一位数字都会被切掉并添加到总和中.

Each time this loop repeats, the last digit is chopped off and added to the sum.

如果左侧小于右侧(对于任何 1 位数字都会发生这种情况),则模运算符返回单个数字,这就是循环中断的时候:

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 % 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).

这篇关于一个数字的数字之和javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:一个数字的数字之和javascript

基础教程推荐