ADD Digits
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?
Solution:
Consider an O (1) algorithm, starting with the simplest number:
0-9 certainly all correspond to return 0-9 on the line.
Next
10 return 1
11 Return 2
12 Return 3
13 Return 4
......
18 Return 9
19 return 1
......
The law is ready, because eventually all the numbers will be mapped to 0-9 of these 10 numbers, so only to start to consider whether such mappings exist some of the laws of nature, then by the above can be found that the law is as the size of the number itself increases, the last map to the number is actually incremental, but this increment is actually 9 As a model, and for this problem we only care about the remainder of the modulus and do not care about the number itself has a few "modulo 9".
One thing to be aware of is:
0 is special here, only 0 of the numbers themselves map to 0, no other numbers are mapped to 0 and need to be handled separately.
So, in fact, we're going to map a number except 0 to 1-9 of these nine numbers, and think about that the result should be (num-1)% 9 + 1.
The code is as follows:
1 classSolution:2 #@param {integer} num3 #@return {integer}4 defadddigits (self, num):5 ifnum = =0:6 return07 Else:8 return(num-1)% 9 + 1
"Leetcode" Add Digits