Total Accepted: 70241
Total Submissions: 146130
Difficulty: Easy
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?
刚开始也并不知知道如何O(1)的时间解决 , 后来查找才知道原来有个数根公式
digits = 1 + ( n - 1 )%9 ;
所以问题就简单了 ,一行 代码就搞定了 。
int addDigits(int num) {
return (num-1)%9+1 ;
}