HDOJ1013解题报告

Digital Roots

Problem Description

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.

Input

The input file will contain a list of positive integers, one per line. The end of the input will be indicated by an integer value of zero.

Output

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

Sample Input

24
39
0

Sample Output

6
3

首先,今天首次采用了c++,出师不利啊,刚开始把文件名写成.c了,悲剧出现了一大堆乱七八糟的错误

后来程序

#include <iostream>
#include <string>


using namespace std;

int getSingleDigit(int n){
    if(n<10)return n;
    int fj[100],index = 0;
    while(n>=10){
        fj[index++]=n%10;
        n = n/10;
    }
    fj[index++] = n;
    n = 0;
    while(index>0)
        n+=fj[--index];
    if(n>=10)
        n=getSingleDigit(n);
    return n;
}

int main(){
    int n=0;
    string str;
    while(cin>>n && n!=0){
        cout<<getSingleDigit(n)<<endl;
    }
    return 0;
}

算出来答案对,却总是wa,幸亏Chris提醒,题目变态(说是integer的但未必,数字可能非常大),然后我换了long还是不行正确的代码如下,应该先把输入给加起来然后递归解决,否则永远wa。。不过也学了点东西。string转int用atoi转long用atol。。嘿嘿。

#include <iostream>
#include <string>


using namespace std;

long getSingleDigit(long n){
    if(n<10)return n;
    int fj[100],index = 0;
    while(n>=10){
        fj[index++]=n%10;
        n = n/10;
    }
    fj[index++] = n;
    n = 0;
    while(index>0)
        n+=fj[--index];
    if(n>=10)
        n=getSingleDigit(n);
    return n;
}

int main(){
    long n=0;
    string str;
    while(cin>>str && str[0]!='0'){
        n = 0;
        //n=atol(str.c_str());
        for(int i=0;i<str.length();i++)
            n+=(str[i]-48);
        cout<<getSingleDigit(n)<<endl;
    }
    return 0;
}
原文地址:https://www.cnblogs.com/shenerguang/p/2320423.html