258. Add Digits

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?

一刷
题解:Digit Root解法
如果进制为b(这道题中为10),输入为n, digit root of n is:

  • dr(n) = 0 if n==0
  • dr(n) = (b-1) if n!=0 and n%(b-1) == 0
  • dr(n) = n % (b-1) if n % (b-1)!=0
    或者:
  • dr(n) = 1 + (n-1) % (d-1)
    因为:
dr(abc) = (a*10^2 + b*10 + c)%9 = (a+b+c)%9
public class Solution {
    public int addDigits(int num) {
        return 1 + (num - 1) % 9;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容