树根 Digital root
数根
(又称数字根Digital root)是自然数的一种性质。换句话说。每一个自然数都有一个数根。数根是将一正整数的各个位数相加(即横向相加),若加完后的值大于等于10的话,则继续将各位数进行横向相加直到其值小于十为止,或是,将一数字反复做数字和,直到其值小于十为止,则所得的值为该数的数根。
比如54817的数根为7。由于5+4+8+1+7=25,25大于10则再加一次。2+5=7,7小于十。则7为54817的数根。
百度百科:http://baike.baidu.com/link?
url=FKQ337jynzKVjYV7X92BZOWW51nI6unO71jOTV1g7gnGKnChCWXkNHB4hqTUCmvrwbPh9voBvMAZcxca3ohAua
维基百科:https://en.wikipedia.org/wiki/Digital_root
leetcode: https://leetcode.com/problems/add-digits/
leetcode原题:
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?
解题思路一:
将数的每一位取出来再相加。再将和的每一位取出来相加。直到和为一个个位数。
代码例如以下:
class Solution { public: int addDigits(int num) { if(num/10==0) return num; int res=0; while(num/10!=0) { res=0; while(num) { int temp=num%10; res+=temp; num/=10; } num=res; } return res; } };解题方法二:
採用有限域的相关知识:
代码例如以下:
class Solution { public: int addDigits(int num) { return 1+(num-1)%9; } };