zoukankan      html  css  js  c++  java
  • digital roots

    题目描述

        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.

    输入描述:

        The input file will contain a list of positive integers, one per line. 
    The integer may consist of a large number of digits.

    输出描述:

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

    输入

    复制
    24
    39
    

    输出

    复制
    6
    3
    #include<iostream>
    #include<string>
    using namespace std;
    string fun(string str)
    {
        int sum = 0;
        string sum_s;
        char ch;
        for(int i=0; i<str.length(); i++)
         {
              ch = str[i];
               //cout<<ch-'0'<<endl;
              sum+=ch-'0';
                
          }
        sum_s = to_string(sum);
        if(sum>0&&sum<=9)
         {
             
             return sum_s;
          }
         else{
             
             return fun(sum_s);
         }
    }
    int main()
    {
        string str;
        int sum;
        char ch;
        while(cin>>str)
        {
            cout<<fun(str)<<endl;
        }
        return 0;
    }

    有没有不用递归解决的办法?

    #include <stdio.h>
    #include <string.h>
    
    int main() {
        char str[10000];
        while (scanf("%s", str) != EOF) {
            if (strcmp(str, "0") == 0) {
                break;
            }
            int answer = 10;//技巧
            while (answer >= 10) {//是大于等于,不是只有大于
                answer = 0;//每次循环归零
                for (int i = 0; str[i] != 0; i++) {
                    answer += str[i] - '0';
                }
                sprintf(str, "%d", answer);//真的很方便啊!!!!
            }
            printf("%d
    ", answer);
        }
    
        return 0;
    }

    参看:https://blog.csdn.net/fuxuemingzhu/article/details/60479349

  • 相关阅读:
    用ASP+DLL实现WEB方式修改服务器时间
    参加了 湖南.NET俱乐部成立大会
    Asp.Net中文本换行
    一直在思考的问题
    GRIDVIEW排序 动态实现和静态实现
    在VS 2005中使用TREEVIEW控件
    GRIDVIEW 中当数据行数未满时,填充空白行
    为了自己的心身健康 合理安排生活 特做了张时间安排表
    在VS 2005后台代码中创建用户控件
    CSS IE7 IE6 Firefox多浏览器兼容(转&摘)
  • 原文地址:https://www.cnblogs.com/ttzz/p/10314933.html
Copyright © 2011-2022 走看看