【重拾计划】模板 | N进制加法

N进制加法模板

基本原理

n进制转十进制,利用字符串处理,由于位数不同,采用倒序处理字符串。

代码实现

#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<cstring>
using namespace std;
const int maxn=300; 
int n;
int a[maxn],b[maxn],c[maxn];
string sumstr(string str1,string str2){
	memset(a,0,sizeof(a));
	memset(b,0,sizeof(b));
	memset(c,0,sizeof(c));
	for(int i=str1.size()-1,j=0;i>=0;i--,j++){
		if(str1[i]>='A' && str1[i]<='F') a[j]=(str1[i]-'A')+10;
		else a[j]=str1[i]-48;
	}
	for(int i=str2.size()-1,j=0;i>=0;i--,j++){
		if(str2[i]>='A' && str2[i]<='F') b[j]=(str2[i]-'A')+10;
		else b[j]=str2[i]-48;
	}
	for(int i=0;i<maxn;i++){
		c[i]+=(a[i]+b[i]);
		if(c[i]>=n){
			c[i+1] += c[i]/n;
			c[i] %= n;
		}
	}
	int p=maxn-1;
	while(c[p]==0 && p>0) p--;
	string t;
	for(int i=p;i>=0;i--){
		if(c[i]>=10) t+=(c[i]-10)+'A';
		else t+=c[i]+'0';	
	}
	return t;
}
int main()
{
	cin>>n;
	string str1,str2;
	cin>>str1; cin>>str2;
	string str3;
	str3=sumstr(str1,str2);
	cout<<str3;
	return 0;
}  

样例

样例1

样例

样例2

样例

复习收获

复习字符串及相关知识,学习N进制加法模板。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值