hdu-1013 Digital Roots

题目来源:hdu-1013

Digital Roots
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 59825 Accepted Submission(s): 18723

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

Source
Greater New York 2000

题目大意:
输入一个数,对其各个位上的数进行运算(相加)所得结果在0~10范围内就停止运算,否则继续对运算结果进行此运算。
解题思路:
首先可由题目知所输入数据为int型,故数字位输小于5,即最多有4位,故最多运算位数可知道。我首先是采用字符型数组,将数字输入此数组中,然后将每一位相加得到一个数,若此数满足条件,直接输出即可;否则,使用一while语句继续运行此操作,当然此操作是在知道最大位数的前提下进行的。
AC代码:

#include<stdio.h>
#include<string.h>
using namespace std;
char sum[1010];
int main()
{
    while(scanf("%s",sum),strcmp(sum,"0"))  //当输入0时结束 
    {
        int temp=0;
        for(int i=0;i<strlen(sum);i++)
            temp+=sum[i]-'0';           //先进行一次操作 
        while(temp>9)                   //若不满足,继续此操作 
        {
            temp=temp%10+(temp/10)%10+(temp/100)%10+(temp/1000)%10;
        } 
        printf("%d\n",temp);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值