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.
Follow up:
Could you do it without any loop/recursion in O(1) runtime?
解答:
给一个非负整数,重复地用它的各个数位进行求和,直到剩下一个数位为止。
从题目分析,每个数位均为0~9的数字,进行求和时,超过9就进位,直到最后一个数不超过9
根据Digital root原理
class Solution {
public:
int addDigits(int num) {
if(num % 9 == 0 && num != 0)
return 9;
else
return (num % 9);
}
};