Digital Roots【北京大学】★

本文介绍了一种快速求解数字根的方法。通过两步处理:首先将输入的大整数拆分成单个数字并求和,如果和大于10,则继续重复此过程直到得到一位数的数字根。该算法简洁高效,适用于2的31次方范围内的任意整数。

牛客网题目链接

解题思路

2的31次方约等于2乘以10的9次方,即十进制最多十位数
数位分解以后,就算是10个9的数位和也才90
所以第一步处理以后,就只剩两位数了,循环计算两位数就行 。

版本1

#include<cstdio>
#include<cstring>
int main(){
	char str[35];
	while(scanf("%s",str)!=EOF&&str[0] != '0'){
		int len = strlen(str);
		int sum = 0;
		for(int i = 0;i < len;i++){
			sum += str[i] - '0';
		} 
		while(1){
			if(sum < 10){
				printf("%d\n",sum);
				break;
			}
			else {
				sum = sum/10 + sum%10; 
			}
		}
	    
	}
    return 0; 
} 

版本2

直接模拟

#include <iostream>
#include <vector>
#include <string>
#include <cmath>
#include <algorithm>
#include <queue>
#include <cstdio>
#include <cctype>
#include <unordered_map>
#include <map>
using namespace std;
const int N = 105;
typedef pair<int, string> PII;
int main() {
	string str;
	while(cin>>str){
		int res = 0;
		for(auto c: str){
			res += c - '0';
		}
		while(res > 10){
			int ans = 0;
			while(res){
				ans += res%10;
				res /= 10;
			}
			res = ans;
		}
		cout<<res<<endl;
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值