您的位置:首页 > 职场人生

leetcode 之 add digits

2016-01-18 23:34 253 查看
题目:

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?

解答:

这是ACM的一个典型的题目,就是digit root

首先要知道一个定理就是一个数模9的余数和它的所有位加起来的和模9的余数相同

证明如下:

假设一个数字为a[n-1].....a[0]

首先1 % 9 = 1 % 9

10 % 9 = 1 % 9

100 % 9 = 1 % 9

........

10^(n - 1) % 9= 1 % 9

两边同时乘以相应的位的值,再相加就有(a[n-1]*10^(n-1)) + ......+ a[0]) % 9 = (a[n-1] + .....a[0]) % 9

即已经证明

这样假设初始为num,f(num)为num的每个位的数字的和

num % 9 = f(num) % 9 = f(f(num)) % 9 =.....=t % 9

t就是最终的结果并且t小于等于9

所以很明显t = num- ((num- 1)/9 )* 9;

代码就是 return
num- ((num- 1)/9 )* 9;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 算法 面试