ZOJ 1115 Digital Roots 水题

这是一篇关于ZOJ 1115题目的博客,作者在解决过程中遇到了错误,从CE到WA,最终发现问题是由于使用int处理大整数导致,解决方案转为使用字符处理。博客提到了两种方法,一种是通过字符处理各个位数的和对9取余,另一种是C++中使用string的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

刚开始的时候,代码里有注释,结果CE。

后来,WA,奇了怪了。挺简单的一道题哇。

事实上是我没考虑大整数,不能用int,得用字符处理。

方法二http://blog.sina.com.cn/s/blog_6ce23f8f0100loc4.html,各个位数的和%9。

# include <stdio.h>
# include <string.h>
int main()
{
	int root;
	char a;
	while(1)
	{
	root=0;
	while(scanf("%c",&a) && a!='\n')
		root+=a-'0';		//所有位数上的数字和
	if(root==0)
		break;
	if(root%9==0)
		root=9;
	else
		root=root%9;
	printf("%d\n",root);
	}
	return 0;
}

 方法一(C++)大学上了两年多,却只能看懂简单的。C++中的string,代码来源:http://blog.youkuaiyun.com/bbplayers/article/details/5714677

// may the input string will be long ,and then 'int' is not long enough
#include<iostream>
#include<string>
using namespace std;
int digitroot( int a)
{
    int dr = 0;
    while( a > 0)
    {
	dr += a%10;
	a /= 10;
    }
    if( dr > 9)
	return digitroot( dr);
    return dr;
}
int main(void)
{
    string s;
    while( cin >> s && s[0] != '0' )
    {
	int a = 0;
	for( int i=0; i< s.length(); i++)
	    a += s[i]-'0';
	cout<<digitroot( a)<<endl;
    }
    return 0;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值