数学公式推导(小学数奥)
$x = \overline{a_{n-1}a_{n-2}…a_{0}} = a_{n - 1} \cdot 10^{n - 1} + a_{n-2} \cdot 10^{n - 2} + … + a_0 * 10^0$
$x = a_{n - 1} \cdot 10^{n - 1}mod9 + a_{n-2} \cdot 10^{n - 2}mod9 + … + a_0 * 10^0mod9 = f(x) (mod9)$
$f(x) = x(mod9)$
$xmod9 = $
- 1-8,则各位相加得1-8
- 0
- 当x = 0,各位相加才得0
- 当x!=x,各位相加得9
时间复杂度$O(1)$
AC代码
class Solution {
public:
int addDigits(int num) {
int res = num % 9;
if (!res && !num) return 0;
if (!res) return 9;
return res;
}
};