Description:
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?
Test instructions is very simple, the easiest way to think of is to loop the iteration, if it is <10 return. The following is a recursive approach.
public class Solution {public int adddigits (int num) { if (num <) { return num; } 1023 int t = 0; while (num >= 1) { t + = num%; num = NUM/10; } return Adddigits (t); }}
So what can I do to reduce the complexity to O (1) without recursion and iteration, which reminds me of the formula. To find patterns through data.
Top 30 Data tests:
public static void Main (string[] args) {for (int i=0; i<30; i++) {System.out.println (i + "+ adddigits (i))}}
0 0
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
21 3
22 4
23 5
24 6
25 7
26 8
27 9
28 1
29 2
Find out the rules.
In fact, this is: (num-1)% 9 + 1
public class Solution {public int adddigits (int num) { return (num-1)% 9 + 1; }}
Leetcode--add Digits