258. Add Digits

题目:

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?

Hint:

    1. A naive implementation of the above process is trivial. Could you come up with other methods?
    2. What are all the possible results?
    3. How do they occur, periodically or randomly?
    4. You may find this Wikipedia article useful.

链接: http://leetcode.com/problems/add-digits/

3/4/2017

不看别人答案绝对做不出来题目中不用循环的要求。

自己的版本:

 1 public class Solution {
 2     public int addDigits(int num) {
 3         if (num < 10) return num;
 4 
 5         int sum = 10;
 6         while (sum >= 10) {
 7             sum = 0;
 8             while (num != 0) {
 9                 sum += num % 10;
10                 num /= 10;
11             }
12             num = sum;
13         }
14         return sum;
15     }
16 }

看别人答案:

1.  (a + b) mod n  = ((a mod n) + (b mod n)) mod n

2.  (a * b) mod n = ((a mod n) * (b mod n)) mod n

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

我觉得这种题没见过就基本不要想按照那个要求来做了,有幸刷到就做,没刷到就爱谁谁。

原文地址:https://www.cnblogs.com/panini/p/6504897.html