一、热身 [Cloned] M - 枚举答案能不能做?

本文介绍了一种计算数字根的方法,即通过不断累加数字直至得到个位数的过程。使用C++实现这一算法,并通过示例解释了如何进行数字根的计算。

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

原题:

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. 

题意:

给出一个数字,要求这个数字的根数字。所谓根数字就是将这个数的所有位数相加,如果不是个位数就继续将所有位数上的数字相加。例如24,则2+4=6;39,3+9=12,不是个位数则继续,1+2=3。

题解:

显然输入的数字需要用字符串表示,但是加和可以直接用int表示(只是试了试,没给数据范围,没想到真的可以),然后别的就没什么好说的了.......直接不断循环加和一直到个位数就行了

代码:AC

#include<iostream>
#include<cstring>
using namespace std;
int main()
{
	char str[1200];
	while(cin>>str)
	{
		if(str[0]=='0')
		{
			break;
		}
		int i,sum=0;
		for(i=0;i<strlen(str);i++)
		{
			sum+=str[i]-'0';
		}
		while(sum>9)
		{
			i=0;
			while(sum>0)
			{
				i+=sum%10;
				sum/=10;
			}
			sum=i;
		}
		cout<<sum<<endl;
	}
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值