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?
<Solution>Could you do it without any loop/recursion in O(1) runtime?
解法一,就是按題目要求做
code 如下
那題目也問說,有沒有 O(1) 的解法
根據觀察
num ans
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
10 1
11 2
12 3
13 4
14 5
15 6
16 7
17 8
18 9
19 1
20 2
可以看出來,是每 9 個會循環,所以答案就會是 ans = (num - 1 ) % 9 + 1
code如下(參考資料)
c++
kotlin
沒有留言:
張貼留言