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

  • 相关阅读:
    异常:Batch update returned unexpected row count from update [0]; actual row count: 0;
    python UI/API 环境配置
    selenium xpath定位
    python webdriver 的安装与下载
    python面试题
    fiddler工具使用及手机抓包
    jmeter 常用函数
    Jmeter常用插件——Stepping Thread Group ,JMETER以及关于数据库性能分析
    Jmeter Monitor监控
    python 常用快捷键
  • 原文地址:https://www.cnblogs.com/ttzz/p/10314933.html
Copyright © 2011-2022 走看看