[LeetCode]Add Digits

来源:互联网 发布:ai软件卡通图片 编辑:程序博客网 时间:2024/06/06 00:29

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?

  1. You may find this Wikipedia article useful.

The formula is:

 \operatorname{dr}(n) = \begin{cases}0 & \mbox{if}\ n = 0, \\ 9 & \mbox{if}\ n \neq 0,\ n\ \equiv 0\pmod{9},\\ n\ {\rm mod}\ 9 & \mbox{if}\ n \not\equiv 0\pmod{9}.\end{cases}

or,

 \mbox{dr}(n) = 1\ +\ ((n-1)\ {\rm mod}\ 9).\

可以采用数学归纳法证明正确性。纯数学题。
class Solution {public:    int addDigits(int num) {        return 1+(num-1)%9;    }};


0 0
原创粉丝点击