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.
给定一个整数,计算各位上的数字的和得到另外一个数字,直到该数字为个位数。
模拟一下就可以得出结果,但是要求o(1)的时间复杂度,找规律!
维基百科地址:Digital root
AC代码:
class Solution {
public:
int addDigits(int num) {
return 1+(num-1)%9;
}
};
其他Leetcode题目AC代码:https://github.com/PoughER/leetcode