• 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;
    
    }
  • 相关阅读:
    Calendar
    Eclipse常用快捷键
    switch case知识点
    Java中基本数据类型和包装类
    SpringMVC初始化参数绑定--日期格式
    spring mvc4使用及json 日期转换解决方案
    Java下利用Jackson进行JSON解析和序列化
    jsp页面中某个src,如某个iframe的src,应该填写什么?可以是html、jsp、servlet、action吗?是如何加载的?
    jdbc入门
    存储过程和触发器
  • 原文地址:https://www.cnblogs.com/malloc/p/2392516.html
Copyright © 2020-2023  润新知