258. Add Digits

来源:互联网 发布:八本兵种等级数据 编辑:程序博客网 时间:2024/06/10 01:13

Given a non-negative integernum, repeatedly add all its digits until the result has only one digit.

For example:

Given num = 38, the process islike: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.

    给定一个非负整数num,重复地添加所有其数字,直到结果只有一个数字。

例如:

    给定num = 38,过程如下:3 + 8 = 11,1 + 1 = 2。由于2只有一个数字,返回它。也就是将他的每一位想加,得到一个大于10的数,然后继续想加,知道只有一个数。在自然数中,只有一个数是9,所有经过参考,可以想到跟9取余。

    这题他说不使用循环或者递归,代码如下:

public class Solution {

    public int addDigits(int num) {

        if(num==0||num==9)

          return num;

        if(num%9==0)

           return 9;

        return num%9;

    }

}

0 0