Add Digits (数根 digital root)

来源:互联网 发布:ubuntu切换到root 编辑:程序博客网 时间:2024/05/29 13:51

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 = 111 + 1 = 2. Since 2 has only one digit, return it.

Follow up:

Could you do it without any loop/recursion in O(1) runtime?


循环求解的方法就不介绍了。

一个数循环相加得到的个位数(digital root, 数根) = 这个数 mod 9


digital root的介绍详见https://en.wikipedia.org/wiki/Digital_root


so

public class Solution {    public int addDigits(int num) {        if (num == 0)        return 0;        if (num % 9 == 0)        return 9;        return num % 9;    }}

简化版

public class Solution {    public int addDigits(int num) {        return 1 + (num - 1)%9;    }}


0 0
原创粉丝点击