0%

add-digits

Add Digits – LeetCode 258

Problem

Description

Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.

Example

Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.

Answer

Original

Code

1
2
3
4
5
6
class Solution {
public:
int addDigits(int num) {
return 1 + (num - 1) % 9;
}
};

思路

纯粹数学题,看Wiki时间复杂度$O(1)$,空间复杂度$O(1)$。
耗时$6$ ms,排名$91.18\%$

Better

思路

还没看到更好的思路