Problem 258

Add Digits

Posted by Ruizhi Ma on June 20, 2019

问题描述

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. Follow up: Could you do it without any loop/recursion in O(1) runtime?

解决思路

给这题跪了,居然有公式,具体看这个博客吧:https://blog.csdn.net/weixin_41514525/article/details/82934619

代码一

package leetcode;

public class AddDigits {
    public int addDigits(int num) {
        return num==0?0:(num%9==0?9:(num%9));
    }
}

问题解惑

有人问我,这个第二个不是递归啊!这哪里是递归啊,这不就是普通的从上到下执行了函数吗?
我一开始也整懵了,好像有点道理?呵呵,这个递归是局部递归,对temp判断进行了递归而已。如果while循环出来的temp > 10,则不断递归,将temp处理到小于10

代码二(递归,但是Time out)

package test;

public class Leetcode {
	public int addDigits(int num) {
        int temp = 0;
        while (num > 0){
            temp += num % 10;
            num /= 10;
        }

        if (temp < 10){
            return temp;
        }else {
            return addDigits(temp);
        }
    }
}