参考博客:参考博客1
——题目描述:
leetcode 258:
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?
——使用O(1)的时间复杂度解决,涉及一个数学推导的过程,如下:
- 假设有一个5位的数字num,每位上的数字分别为a,b,c,d,e,则num可以表示为:
num = a *10000 + b *1000 + c *100 + d *10 + e
num = (a+b+c+d+e) + (a*9999 + b*999 + c*99 + d*9)
w = (a+b+c+d+e)
H = (a*9999 + b*999 + c*99 + d*9)
num = W + H
- 我们知道,H肯定可以被9整除,所以有以下关系:
num % 9 == W % 9
- 然后我们如果继续对W反复多次采用处理num的方式,则会有下面这种形式,U是一个0-9之间的数字,N可以被9整除。所以这里的U就是我们这道题里最后求的那个各位相加后的和,且这个和是个位数。
W = U + N
- 由于我们已知有如下关系:
(x + y) % z == (x % z + y % z) % z
x % z % z == x % z
- 因此可以得到,
U = num % 9
——因此,C++代码如下:
int addDigits(int num) {
if (num == 0)
return 0;
else if (num % 9 == 0)
return 9;
else
return num % 9;
}
——Python代码如下:
def addDigits(num):
if num == 0:
return 0
elif num % 9 == 0:
return 9
else:
return num % 9
——-当然,如果把num等于0和整除9的情况都统一起来的话,也可以写成如下:
int addDigits(int num) {
return (num - 1) % 9 + 1;
}