Digital Roots

Digital Roots

Describe
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

此题没有给出数据范围是一大坑点,数据范围应该是贼大,不然不会一直WA……下面是一开始的小范围数据的代码。

#include<iostream>

using namespace std;

long long root(long long num);

int main()
{
    long long num;
    while(cin>>num&&num)
    {
        cout<<root(num)<<endl;
    }   
    return 0;
}

long long root(long long num)
{
    long long n=num%10,temp=0;
    if(num/10==0)
        return num;

    else
    {
        while(n||num)
        {
            temp+=n;
            num/=10;
            n=num%10;
        }
        return root(temp);
    }
}

然后是改了之后AC的代码。

#include<iostream>
#include<cstdio>
#include<cstring>

using namespace std;

int root(int num[],int len);

int main()
{
    char str[1000]={0};
    int num[1000]={0};
    while(scanf("%s",str))
    {
        int len=strlen(str),res;
        for(int i=0;i<len;i++)  num[i]=str[i]-'0';
        res=root(num,len);
        if(!res) break;
        cout<<res<<endl;
    }   
    return 0;
}

int root(int num[],int len)
{
    int n=0,i;
    if(len==1)
        return num[0];

    else
    {
        for(i=0;i<len;i++)
            n+=num[i];

        i=0;    
        while(n)
        {
            num[i]=n%10;
            n/=10;
        i++;
        }
        return root(num,i);
    }
}

然后是应用数根公式的终极版代码。

#include<cstdio>
int main()
{
    char str[1001];
    int i, sum;
    while(scanf("%s",str))
    {
        if(str[0]=='0')
            break;
        for(i=0,sum=0;str[i]!='\0';i++)
            sum+=str[i]-'0';
        printf("%d\n",(sum-1)%9+1);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值