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 | class Solution { |
有趣的是同样的代码Java比C++和C都跑得快