leetcode解题报告258——Add Digits

来源:互联网 发布:精算师 知乎 编辑:程序博客网 时间:2024/06/04 20:14

题目:
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?

思路:
用递归方法,代码如下。
但是题目说了不建议用递归。

public int addDigits(int num) {        if (num < 10) {            return num;        }        int res = 0;        while (num > 0) {            res += num % 10;            num = num / 10;        }        return addDigits(res);    }

找规律(第一行为输入数字,第二行为数字的叠加和)

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 0 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2

规律:除了第一个数字0外,呈现从1~9循环的规律。

代码:

public int addDigits4(int num) {        if (num == 0) {            return 0;        }        int res = num % 9;        if (res == 0) {            return 9;        } else {            return res;        }}
0 0