[leetcode] 258. Add Digits

来源:互联网 发布:井冈山大学网络平台 编辑:程序博客网 时间:2024/05/01 01:54

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.

这道题是求数根,题目难度为Easy。

这是一道纯数学知识的题目,不了解数根的同学可以看下wiki上的页面。数根求值公式为dr(n) = ((n-1) mod 9)+1。由于10^k ≡ 1^k≡ 1 mod 9,所以n ≡ dr(n) mod 9。这里编辑公式太麻烦,对证明过程还有疑问的同学可以看下文章结尾给出的知乎上的证明。具体代码:

class Solution {public:    int addDigits(int num) {        return (num - 1) % 9 + 1;    }};
知乎页面:http://www.zhihu.com/question/30972581

0 0