[LeetCode-258]Add Digits(java)

来源:互联网 发布:java输出1到100的素数 编辑:程序博客网 时间:2024/05/22 11:43

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?
题目意思是:
对于任意一个非负整数,将其各位上的数字依次不断相加,最后总会得到一个个位数,现给出任意一个非负整数,求出最终的个位数。
例如:num=123456,则(1+2+3+4+5+6)=11=(1+1)=2,即最终的个位数为2。

这里涉及到数学里面的Digital root

  • 对于任意一个数,例如123456=1*100000+2*10000+3*1000+4*100+5*10+6
    =1*(99999+1)+2*(9999+1)+3*(999+1)+4*(99+1)+5*(9+1)+6
    =(1*99999+2*9999+3*999+4*99+5*9+2*9+3
    =3 mod 9
  • num=0时,digital root=0
  • num!=0,例如num=36=3+6=9=0 mod 9
  • 即对于任意一个数num有,如果num=0,digital root=0;
  • 如果num!=0,且num%9=0,则digital root=9;
  • 如果num!=0,且num%9!=0,则digital root=num%9。

分析完成后,具体实现的代码很简单,如下。

public class Solution {    public int addDigits(int num) {        if(num==0)        return 0;        else if(num%9==0)        return 9;        else        return num%9;    }}
0 0
原创粉丝点击