【1402】数字根

描述:

一个正整数的数字根是指该数字各位数字之和,如果和是一个个位数,那么这个数字就是它的数字根,如果和是个两位或多于两位的数字,那么就继续求和直到得到个位数。
例如:数字24,把2和4相加,得到6,那么6就是24的数字根;又比如数字39,把数字3和9相加,得到12,因为12时是两位数,所以继续把1和2相加,得到3,于是3就是39的数字根。
The digital root of a positive integer is found by summing the digits of theinteger. If the resulting value is a single digit then that digit is thedigital root. If the resulting value contains two or more digits, those digitsare summed and the process is repeated. This is continued as long as necessaryto obtain a single digit.
For example, consider the positive integer 24. Adding the 2 and the 4 yields avalue of 6. Since 6 is a single digit, 6 is the digital root of 24. Nowconsider the positive integer 39. Adding the 3 and the 9 yields 12. Since 12 isnot a single digit, the process must be repeated. Adding the 1 and the 2 yeilds3, a single digit and also the digital root of 39.

输入:

输入一个正整数,
input a positive integer,

输出:

输出它的数字根。
Output its digital root.

输入样例:

39

输出样例:

3

 

//这种算法只适用于数比较小的情况。2018.8.9

#include<iostream>
using namespace std;
int main()
{
	int n,a,s=0;
	cin>>n;
	while(n>=10)
	{
		a=n%10;
		n=n/10;
		s=s+a;
	}
	s=s+n;
	while(s>=10)
	{
		a=s%10;
		n=s/10;
		s=n+a;
	}
	cout<<s<<endl;
	return(0);
}

 

//输入的数字比较大时要换一种方法做。。

#include <cstdio>
#include <cstdlib>

using namespace std;

int main()
{
    int s=0;
    char a;
    while(1)
    {
        a=getchar();
        if(a=='\n')
        {
            s=s%9;
            if(s!=0) printf("%d\n", s);
            else printf("9\n");
            break;
        }
        else s=s+a-'0';
    }
	return 0;
}

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值