来源

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/add-digits/

描述

给定一个非负整数 num,反复将各个位上的数字相加,直到结果为一位数。
示例:
输入: 38
输出: 2
解释: 各位相加的过程为3 + 8 = 11, 1 + 1 = 2。 由于 2 是一位数,所以返回 2。
进阶:
你可以不使用循环或者递归,且在 O(1) 时间复杂度内解决这个问题吗?

题解

这套题的本质:如何证明一个数的数根(digital root)就是它对9的余数

  1. class Solution {
  2. public int addDigits(int num) {
  3. if (0 == num) {
  4. return 0;
  5. }
  6. int res = num % 9;
  7. return (res == 0) ? 9 : res;
  8. }
  9. }

参考

https://blog.csdn.net/ray0354315/article/details/53991199