javascript - 我在控制台中不断得到一堆数字作为我的输出
问题描述
我正在研究这个问题:
给定一个非负整数 num,重复添加它的所有数字,直到结果只有一位。
例子:
输入:38 输出:2 解释:这个过程是这样的:3 + 8 = 11, 1 + 1 = 2。由于 2 只有一位,所以返回它。
这是我的代码:
const addDigits = (num) => {
while(num > 9){
let strNum = num.toString()
let count = 0;
console.log(strNum)
for(let i = 0; i < strNum.length; i++){
count += Number(strNum[i])
//while number is greater than 9 we have to keep going
}
}
num = count
console.log(num)
};
addDigits(38)
我在控制台中不断收到一堆数字,而不是所需的输出。有人可以告诉我代码有什么问题吗?
解决方案
您需要num = count
在每次循环迭代结束时设置,而不是在循环外设置。
const addDigits = (num) => {
while(num > 9){
let strNum = num.toString()
let count = 0;
console.log(strNum)
for(let i = 0; i < strNum.length; i++){
count += Number(strNum[i])
//while number is greater than 9 we have to keep going
}
num = count; //moved to last statement of each iteration
}
console.log(num)
};
addDigits(38)
推荐阅读
- scala - 为 scala 2.12.11 添加 tensorflow 依赖项时遇到问题
- javascript - 来自 props 构造函数事件侦听器的本机调用函数
- javascript - 如何在两个或多个项目之间共享代码
- c++ - gdb `list` 命令在附加到进程时仅显示一个行号而不是内容
- python - 更快地从字典中获取元素
- android - 三星 A30s 与 ARCore 不兼容,即使有谷歌要求
- c++ - 从类方法中清除 raylib 中的背景会使窗口闪烁
- javascript - 自动删除 textarea 上的文本
- bash - nohup 什么时候关闭终端不生效 结束后台运行的进程?
- php - 如何更改 laravel 工作时间