
问题 : >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?
这个问题,需要用到这一篇维基百科文章。
C++ :
|
|
这道题的就是求 Digit Root (这里简称 DR )。求 DR 有公式可以求,其利用的技巧是10的幂数对9求余结果总是1。以上的求 DR 过程就可以看成是分部对9求余的过程。这一性质可以用以下的公式描述。
displaystyle
text{dr}(abc) = acdot10^2+bcdot10+ccdot1=a+b+c
求DR的公式:
displaystyle
text{dr}(n) =
begin{cases}
0,&text{if$n=0$,} \
9,&text{if$nneq0,n%9=0$,} \
n%9,&text{if$n%9neq0$.}
end{cases}




近期评论