Given a non-negative integer num
, repeatedly add all its digits until the result have only one digit.
For example:
Givennum = 38
, the process is like:3 + 8 = 11
,1 + 1 = 2
. Since2
have only one digit, return it.
Follow up:
Could do it without any loop/recursion in O (1) runtime?
Problem Solving Analysis:
Solution One:
The remainder is added to Num, and the remainder is added until NUM is less than two digits.
#-*-Coding:utf-8-*-__author__ = ' Jiuzhang ' class solution (object): def adddigits (self, num): While num >= 10 : num = (NUM/10) + num% return num
Solution Two:
The other method is relatively simple and can be illustrated by examples. Assuming that the number entered is a 5 digit num,
Num's members are A, B, C, D, E, respectively. Has the following relationship: num = A * 10000 + b * + + c * + + D * + E
That is: num = (A + B + C + D + E) + (A * 9999 + b * 999 + c * + D * 9)
Because A * 9999 + b * 999 + c * + D * 9 must be divisible by 9, so the num modulo results in addition to 9
The result is the same as a + B + C + D + E modulo except 9. Perform the same operations on the number A + B + C + D + E repeatedly,
The final result is a 1-9 number plus a bunch of numbers, the leftmost number is 1-9, the right number is always
Can be divisible by 9.
Attention:
To handle special cases, when the number is 0, please return directly to 0
#-*-Coding:utf-8-*-__author__ = ' Jiuzhang ' class solution (object): def adddigits (self, num): if num > 0:
return 1 + (num-1)% 9 else: return 0
(leetcode) Add Digits---integers everybody add