leetcode:Add Digits 【Java】

一、问题描述

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 = 111 + 1 = 2. Since 2 has only one digit, return it.

Follow up:
Could you do it without any loop/recursion in O(1) runtime?

二、问题分析

使用递归算法。

实现的算法不足:使用了递归和循环,没有达到时间复杂度O(1),要达到该时间复杂度度请参考https://en.wikipedia.org/wiki/Digital_root

三、算法代码

public class Solution {
    public int addDigits(int num) {
        int sum = 0;
		while(num != 0){
			sum += num % 10;
			num /= 10;
		}
		if(sum >= 10){
			sum = addDigits(sum);
		}
		return sum;
    }
}


你可能感兴趣的:(LeetCode)