Day6. Add Digits(258)

最难忘记的一道,

问题描述
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;
};
    原文作者:前端伊始
    原文地址: https://www.jianshu.com/p/be321ef910be
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞