hdu1013(Digital Roots)

本文介绍了一个简单的C++程序,用于计算输入正整数的数字根。通过不断将数字相加直至结果为一位数的过程来实现。注意处理大整数的情况。

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

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;

const int maxlen = 10000;
char a[maxlen];
//Accepted	1013	0MS	244K	630 B	C++	Achiberx

int get(int a) {
    int s=0;
    while(a) {
        s += a%10;
        a /= 10;
    }
    if(s>9) {
        return get(s);
    }
    else {
        return s;
    }
}

int work() {
    int len = strlen(a);
    int s = 0;
    for(int i = 0; i < len; i++) {
        int tmp = a[i] - '0';
        s += tmp;
    }
    return get(s);
}

int main() {
    while(scanf("%s", a) != EOF) {
      if(a[0] == '0') break;
      int res = work();
      printf("%d\n", res);
    }
    return 0;
}

简单的水题,注意一下,正整数可能会很多远远超过int。。。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值