Chinaunix首页 | 论坛 | 博客
  • 博客访问: 350724
  • 博文数量: 122
  • 博客积分: 5000
  • 博客等级: 大校
  • 技术积分: 1191
  • 用 户 组: 普通用户
  • 注册时间: 2009-10-24 11:12
文章分类

全部博文(122)

文章存档

2010年(122)

我的朋友

分类: C/C++

2010-03-21 00:01:20

一、问题描述

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

二、解题思路

将输入的整数按位全部求和,然后再求该和的根。

三、代码

 

#include<iostream>
#include<string>
using namespace std;
int getDigit(int n)
{
    int sum=0;
    while(n>0)
    {
        sum+=(n%10);
        n/=10;
    }
    return sum;
}
int main()
{
    
    string str;
    int i;
    int n=0;
    cin>>str;
    for( i=0;i<str.size();++i)
        n+=(str[i]-48);
    while(n!=0)
    {
        while(n>=10)
            n=getDigit(n);
        cout<<n<<endl;
        cin>>str;
        n=0;
        for( i=0;i<str.size();++i)
            n+=(str[i]-48);
    }
    return 0;
}


阅读(889) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~