Day6. Add Digits(258)

作者: 前端伊始 | 来源:发表于2017-11-08 22:35 被阅读0次

最难忘记的一道,

问题描述
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;
};

文末彩蛋


Day6. Add Digits(258)

相关文章

  • Day6. Add Digits(258)

    最难忘记的一道, 问题描述Given a non-negative integer num, repeatedly...

  • Leetcode PHP题解--D69 258. Add Dig

    D69 258. Add Digits 题目链接 258. Add Digits 题目分析 给定一个数字,给每一位...

  • 258 Add Digits

    原题链接:Add Digits 这是一道数学题,代码如下: 我不讲解这道题,大家直接看下面这张图就能明白了。

  • 2019-02-02

    LeetCode 258. Add Digits Description Given a non-negative...

  • 258. Add Digits

    258. Add Digits[思路]数字累加,将给定的一个整数,将个位,十位,百位等相加,连续操作,直到最后的值...

  • 258. Add Digits

    循环: 这个办法很神奇

  • 258. Add Digits

    Problem Given a non-negative integer num, repeatedly add ...

  • 258. Add Digits

    问题 Given a non-negative integer num, repeatedly add all i...

  • 258. Add Digits

    1.描述 Given a non-negative integer num, repeatedly add all...

  • [LeetCode 258] Add Digits

    Given a non-negative integer num, repeatedly add all its ...

网友评论

    本文标题:Day6. Add Digits(258)

    本文链接:https://www.haomeiwen.com/subject/qdvsmxtx.html