题目链接:https://leetcode.com/problems/add-digits/
题目:
num
, repeatedly add all its digits until the result has only one digit.
For example:
num = 38
, the process is like: 3 + 8 = 11
, 1 + 1 = 2
. Since 2
Follow up:
Could you do it without any loop/recursion in O(1) runtime?
Hint:
- A naive implementation of the above process is trivial. Could you come up with other methods?
- What are all the possible results?
- How do they occur, periodically or randomly?
- You may find this Wikipedia article useful.
思路:
1、暴力
2、举例说明一下。假设输入的数字是一个5位数字num,则num的各位分别为a、b、c、d、e。有如下关系:num = a * 10000 + b * 1000 + c * 100 + d * 10 + e 。即:num = (a + b + c + d + e) + (a * 9999 + b * 999 + c * 99 + d * 9) , a * 9999 + b * 999 + c * 99 + d * 9 一定可以被9整除,将num的每一位反复相加的结果即和将num模9的结果是一样的。
算法1:
1. public int addDigits(int num) {
2. while (num / 10 != 0) {
3. char[] nums = Integer.toString(num).toCharArray();
4. 0;
5. for (int i = 0; i < nums.length; i++) {
6. num += Integer.parseInt(String.valueOf(nums[i]));
7. }
8. }
9. return num;
10. }