数字javascript的数字之和 [英] sum of the digits of a number javascript

查看:76
本文介绍了数字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));

我得到了正确答案,我只是不完全理解第二个功能,即声明。任何帮助将不胜感激。谢谢!

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.

少数字替代方案是:

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的数字之和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆