258. Add Digits

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?

非负整数各位相加,直到剩下最后一位。

简单的思路如下:

假设我们有一个函数sum(a)

这个函数可以处理a的每一位相加那么实现如下

if(sum(a)>9) return sum(sum(a))

else return sum(a)

但是现在的要求是时间复杂度为o(1)

先上代码

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

思路如下,首先返回值一定是0-9。那么考虑简单情况,例如一个3位数abc,原值为t1=(100a+10b+c) 经过一步各位累加的值为t2=(a+b+c),如果t2<9那么就是t2,而t1-t2一定能被9整除,所以返回值即t1除以9的余数

那么考虑特殊情况,整除返回应该是9而不是0,0返回是0.即可得到答案 

原文地址:https://www.cnblogs.com/icysnow/p/5868840.html