hdu 1013 Digital Roots(字符输入,字符串处理)

43 篇文章 0 订阅

 

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

 

 

 

题目意思大家都很容易理解。题目没有说数据范围,也算是一个坑点吧。

首先第一眼看了就觉得水题,两下写好了如下错误答案:

 

#include <iostream>
#include <queue>
#include <string.h>
#include <string>
#include <algorithm>
#include <map>
#include <cstdio>
using namespace std;
long long int jiejue(long long int a)
{
    int ans=0;
    while(a>0)
    {
        ans+=a%10;
        a=a/10;
    }
    if(ans>=10)
        return jiejue(ans);
    else
    return ans;
}

int main()
{
   int n;
   while(cin>>n)
   {
       if(n==0)
        break;
      cout<<jiejue(n)<<endl;

   }

    return 0;
}

设立了一个解决函数,不断取余相加,加完后再判断是否需要重复运行。代码也容易看懂。

 

但是第一发wa了,然后我就想这么简单的题目不可能wa,那应该是范围问题了

直接开字符输入,处理加出第一次的和,然后再用函数,肯定不会爆。

 

while(scanf("%c",&a))
   {
       if(ok==0&&a=='0')
        break;
       if(a=='\n')
       {
           cout<<jiejue(b)<<endl;
           b=0;
           ok=0;
        continue;
       }
        b+=int(a-'0');
        ok=1;
   }

 

字符判断:   1:接收到回车,开始将之前得到的数据b带入函数运算

                     2 : 接收到0,就break,程序直接结束

                     3:如果都不是,则把这个字符转成整形相加到b

下面贴上完整代码:

 

#include <iostream>
#include <queue>
#include <string.h>
#include <string>
#include <algorithm>
#include <map>
#include <cstdio>
using namespace std;
long long int jiejue(long long int a)
{
    int ans=0;
    while(a>0)
    {
        ans+=a%10;
        a=a/10;
    }
    if(ans>=10)
        return jiejue(ans);
    else
    return ans;
}

int main()
{
   long long int ans,b=0,ok=0;
   char a;
   while(scanf("%c",&a))
   {
       if(ok==0&&a=='0')
        break;
       if(a=='\n')
       {
           cout<<jiejue(b)<<endl;
           b=0;
           ok=0;
        continue;
       }
        b+=int(a-'0');
        ok=1;
   }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值