Digital Roots

Digital Roots


Time Limit: 2 Seconds      Memory Limit: 65536 KB


Background
The digital root of a positive integer is found by summing the digits of the integer. If the resulting value is a single digit then that digit is the digital root. If the resulting value contains two or more digits, those digits are summed and the process is repeated. This is continued as long as necessary to obtain a single digit.
For example, consider the positive integer 24. Adding the 2 and the 4 yields a value of 6. Since 6 is a single digit, 6 is the digital root of 24. Now consider the positive integer 39. Adding the 3 and the 9 yields 12. Since 12 is not a single digit, the process must be repeated. Adding the 1 and the 2 yeilds 3, a single digit and also the digital root of 39.

Input
The input file will contain a list of positive integers, one per line. The end of the input will be indicated by an integer value of zero.

Output
For each integer in the input, output its digital root on a separate line of the output.

Example
Input

24
39
0

Output

6
3

 


Source: Greater New York 2000

 

 

这题是BUG,绝对的陷阱!乍一看,仿佛蛮简单的嘛,一个递归就可以了(注意,仅在限制整形大小的时候可以用,如果是没有上线大小的数字,绝对不能这么算),代码如下:

#include<iostream>
using namespace std;
unsigned long FindRoot(unsigned long digit)
{
  if(digit < 10)
    return digit;
  unsigned long sumAllUp = 0;
  for(;digit;digit /= 10)
    sumAllUp += digit%10;
  return FindRoot(sumAllUp);
}

int main()
{
  unsigned long digit;
  while(cin>>digit && digit)
  {
    cout<<FindRoot(digit)<<endl;
  }
  return 0;
}

 

如果考虑到数字有可能查出上线的话,就只能利用类似大数加这样的算法了,代码如下:

#include<iostream>
#include<string>
using namespace std;
int main()
{
  string s;
  while(cin>>s && s != "0")
  {
    int digitRoot = 0;
    for(int s_index = 0; s_index < s.length(); s_index++)
    {
      digitRoot += (s[s_index] - '0');
      if(digitRoot > 9)
      {
        digitRoot = digitRoot%10 + digitRoot/10;
      }
    }
    cout<<digitRoot<<endl;
  }
  return 0;
}
posted @ 2012-03-12 21:49  Gavin Lipeng Ma  阅读(956)  评论(0编辑  收藏  举报