sum of the digits of a number 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


- Flexslider 箭头未正确显示 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- 400或500级别的HTTP响应 2022-01-01