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

  • 相关阅读:
    数据结构与算法分析
    案例分析作业
    实验六——循环结构程序练习总结
    实验五——循环结构学习总结
    实验四——多分支结构及本章总结
    实验三——for 语句及分支结构else-if
    第二次作业及总结——数据类型和运算符
    2-c语言作业
    自然博物馆参观
    2019-2020-1学期 20192409《网络空间安全专业导论》第四周学习总结
  • 原文地址:https://www.cnblogs.com/ttzz/p/10314933.html
Copyright © 2011-2022 走看看