• 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

  • 相关阅读:
    LaunchScreen.storyboard 换了图片 不能更改过来 解决方案
    iOS Google 地图 集成详解
    Mac下 使用git clone 代码慢解决方案
    iOS 函数式编程
    iOS [self class] 、 [self superclass]、 [super class] 、[super superclass] 几种情况对比
    iOS 链式编程-Block 作为放回值
    iOS block的变量捕获(capture)
    iOS Block本质探究
    iOS 读写操作 处理 pthread_rwlock dispatch_barrier_async
    iOS atomic 和 nonatomic 区别
  • 原文地址:https://www.cnblogs.com/ttzz/p/10314933.html
Copyright © 2020-2023  润新知