题解 | a+b

#include<iostream>
#include<climits>
#include<string>
#include<sstream>
using namespace std;

/*
 *大数加法a+b
 * */
int main(){
	int* a = NULL;
      	int* b = NULL;
	int* ans = NULL;
	string s1, s2;
	while(cin>>s1>>s2){
		int n1 = s1.length();
		int n2 = s2.length();
		a = new int[n1];
		b = new int[n2];
		ans = new int[1000];
		//初始化数组
		for(int i = 0; i<n1;i++){
			a[i] = s1[n1-i-1] - '0';
		}
		for(int i = 0; i<n2;i++){
			b[i] = s2[n2-i-1] - '0';
		}
		for(int i = 0;i<1000;i++){
			ans[i] = INT_MAX;
		}
		//相加
		bool flag = false;	//是否进位
		if(n1>=n2){
			for(int i = 0;i<n2;i++){
				if(flag){
					ans[i] = a[i] + b[i] + 1;
					flag = false;
					if(ans[i]>=10){
						ans[i] = ans[i]%10;
						flag = true;
					}
				}else{
					ans[i] = a[i] + b[i];
					if(ans[i]>=10){
						ans[i] = ans[i]%10;
						flag = true;
					}
				}
			}
			for(int i = n2;i<n1||flag;i++){
				if(flag){
					if(i<n1){
						ans[i] = a[i] + 1;
						flag = false;
						if(ans[i]>=10){
							ans[i] = ans[i]%10;
							flag = true;
						}
					}else{
						ans[i] = 1;
						flag  = false;
					}
				}else{
					ans[i] = a[i];
				}
			}
		}else{
			for(int i = 0;i<n1;i++){
				if(flag){
					ans[i] = a[i] + b[i] + 1;
					flag = false;
					if(ans[i]>=10){
						ans[i] = ans[i]%10;
						flag = true;
					}
				}else{
					ans[i] = a[i] + b[i];
					if(ans[i]>=10){
						ans[i] = ans[i]%10;
						flag = true;
					}
				}
			}
			for(int i = n1;i<n2||flag;i++){
				if(flag){
					if(i<n2){
						ans[i] = b[i] + 1;
						flag = false;
						if(ans[i]>=10){
							ans[i] = ans[i] % 10;
							flag = true;
						}
					}else{
						ans[i] = 1;
						flag = false;
					}
				}else{
					ans[i] = b[i];
				}
			}
		}
		//输出
		ostringstream oss;
		for(int i = 999;i>=0;i--){
			if(ans[i]!=INT_MAX){
				oss<<ans[i];
			}
		}
		cout<<oss.str();
	}
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务