您的位置:首页 > 其它

hdu-1013 Digital Roots

2015-09-12 10:44 381 查看
题目来源: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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: