首页 > 解决方案 > 我在控制台中不断得到一堆数字作为我的输出

问题描述

我正在研究这个问题:

给定一个非负整数 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)

我在控制台中不断收到一堆数字,而不是所需的输出。有人可以告诉我代码有什么问题吗?

标签: javascriptalgorithm

解决方案


您需要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)


推荐阅读