Sunday, August 16, 2015

258 - Add Digits

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 = 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?
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.
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
Hide Tags
Math
Hide Similar Problems
(E) Happy Number

在草稿纸上写一下10~30,很快发现规律:结果是1~9不断循环,所以肯定就是直接对 9 求余了。
除了两种情况:小于 10,返回自己,大于 10 但能被 9 整除,返回 9 而不是 0。

class Solution {
public:
    int addDigits(int num) {
        return (num>9) ? ((0==num%9) ? 9: num%9) : num;
    }
};
8 ms.

No comments:

Post a Comment