1. 程式人生 > >PAT乙級1074【宇宙無敵加法器】 進位制加法 reverse

PAT乙級1074【宇宙無敵加法器】 進位制加法 reverse

先掛上題目連結~https://www.patest.cn/contests/pat-b-practise/1074

分析: STL的reverse函式很好用a,注意最後一位的c不為0時高位要補上。。

程式碼:

#include<bits/stdc++.h>
#include<string>
using namespace std;
char radix[100];
char s1[100],s2[100];
int res[100];
//#define loc

int main(){
	int c=0,len1,len2;
	#ifdef loc
		freopen("in.txt", "r", stdin);
		freopen("out.txt", "w", stdout);
	#endif
	scanf("%s", radix);
	scanf("%s", s1);
	scanf("%s", s2);
	len1 = strlen(s1);
	len2 = strlen(s2);
	reverse(radix, radix+strlen(radix));
	reverse(s1, s1+len1);
	reverse(s2, s2+len2);
	int i = 0;
	for(i = 0; i<min(len1, len2); i++){
		int tem = s1[i]-'0'+s2[i]-'0'+c;
		int temr = radix[i]-'0';
		if(temr == 0) temr = 10;
		c = tem/temr;
		tem -= c*temr;
		res[i] = tem;
	}
	while(i < len1){
		int tem = s1[i]-'0'+c;
		int temr = radix[i]-'0';
		if(temr == 0) temr = 10;
		c = tem/temr;
		tem -= c*temr;
		res[i] = tem;
		i++;
	}
	while(i < len2){
		int tem = s2[i]-'0'+c;
		int temr = radix[i]-'0';
		if(temr == 0) temr = 10;
		c = tem/temr;
		tem -= c*temr;
		res[i] = tem;
		i++;
	}
	if(c != 0) res[i++] = c; //別忘了加上最後一位,否則有兩個測試點過不去 
	reverse(res, res+i);
	int idx = 0;
	while(idx<i && res[idx] == 0) idx++;
	if(idx == i){
		printf("0");//特判結果是否為0 
		return 0;
	}
	for(int j = idx; j<i; j++)
		printf("%d", res[j]);
		
	return 0;
}