ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. Example: ``` Input: 38 Output: 2 Explanation: The process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it. ``` ``` 思路1:先把数字变为字符串,然后把字符串转化为一个数组。最后用递归或者循环都可以 /** * @param {number} num * @return {number} */ var addDigits = function(num) { if(num<10){ return num; } else{ str = num + ''; var arr = str.split(''); var sum = 0; for(var i = 0; i <arr.length; i++){ sum += parseInt(arr[i]); } return addDigits(sum); } }; ``` ``` /** * @param {number} num * @return {number} */ var addDigits = function(num) { if (num > 0 && num % 9 === 0) return 9; return num % 9; }; ```