• 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

  • 相关阅读:
    【转】Install libimobiledevice on Mac OSX
    【转】Mac端包管理工具——Homebrew简介及安装
    Appium的安装-Mac平台(命令行 & dmg)
    【转】NO.3、python+appium+ios,遍历真机元素,得到webview
    【转】NO.2、Appium之IOS第一个demo
    【转】NO.1、 appium之ios环境搭建
    如何在 iOS 真机运行 Appium
    【转】adb shell dumpsys 命令
    Mac下抓包工具charles及破解方法
    2017.08 笔记
  • 原文地址:https://www.cnblogs.com/ttzz/p/10314933.html
Copyright © 2020-2023  润新知