最难忘记的一道,
问题描述
Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
For example:
Given num = 38, 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);
}
};
思路2:为什么要对9求余,我已经忘记了,当初教我的人儿也因为我太笨放弃了我
/**
* @param {number} num
* @return {number}
*/
var addDigits = function(num) {
if (num > 0 && num % 9 === 0) return 9;
return num % 9;
};