258. Add Digits

Total Accepted: 67030
Total Submissions: 139534
Difficulty: Easy

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:

A naive implementation of the above process is trivial. Could you come up with other methods?

O(1)的话自然不能用循环了,答案就是余九之后的结果,但除了0之外9的倍数的话都还是9,所以改动一下减1再余九再加一即可。

C++:

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

有趣的是同样的代码Java比C++和C都跑得快

打个小广告

欢迎加入我的小专栏「基你太美」一起学习。