Problem:
Given a non-negative integer num
, repeatedly add all its digits until the result have only one digit.
For example:
Given num = 38
, the process is like: 3 + 8 = 11
, 1 + 1 = 2
. Since have only one 2
digit, return it.
Follow up:
Could do it without any loop/recursion in O (1) runtime?
The original idea is to add and judge the repeated loops until a satisfied solution is found. By referring to other people's answers, we find that the problem is to ask for "number root".
This method is judged by the cyclic addition until a viable solution is found:
classSolution { Public: intAdddigits (intnum) { intAdd =0; while(Num >=Ten) { while(Num >0) {Add+ = num%Ten; Num/=Ten; } num=add; } returnnum; }};
However, due to the complexity of time exceeds the requirements of the topic, it is considered to the "number root" solution.
The enumeration indicates that:
10 1+0 = 1
11 = 2
12 1+2 = 3
13 1+3 = 4
14 1+4 = 5
15 1+5 = 6
16 1+6 = 7
17 1+7 = 8
18 1+8 = 9
19 1+9 = 1
20 2+0 = 2
So we can draw a regular, every 9 cycles. To handle a multiple of 9, we write as (n-1)% 9 + 1. This can be done by:
class Solution {public: int adddigits (int num) { return 1 9 1 ; }};
Leetcode 258. ADD Digits