原题:
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?
大意:一个非负整数,重复的将它的每个位上的值相加直到该值为一位数。
举例:num = 38,过程如下:3+8 = 11;1+1 =2;2就是需要返回的值。
本来此题可以通过模拟法进行举例实现,但题主要求在O(1)时间复杂度的情况下返回值,所以需要进行数学归纳。
从最简单的开始:1-9的返回值对应的为1-9;10-19对应的是1-9;20-29对应的是2-9-1;以此类推。
最后我们发现,一个再大的数字,除了其个位数外,其他位的数只不过浮云!所以结果就出来了,拿到这个非负整数对9取余数,如果不等于0则直接返回余数,等于零则返回9。