本文主要是介绍51nod 1005: 大数加法(含符号),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
给出2个大整数A,B,计算A+B的结果。
Input
第1行:大数A 第2行:大数B (A,B的长度 <= 10000 需注意:A B有可能为负数)
Output
输出A + B
Input示例
68932147586 468711654886
Output示例
537643802472
#include<bits/stdc++.h>
using namespace std;
string bigSub(const string a,const string b){int lena = a.size();int lenb = b.size();int max_len = lena > lenb ? lena : lenb;vector<char> res;res.resize(max_len);int flag = 1;//默认a大于等于bif(lena < lenb || (lena == lenb && a < b)){flag = 0;//b > a}if(flag){ // a >= b时候 for(int i = 0; i < lenb; ++i){res[i] = a[lena-i-1]-b[lenb-i-1];//保存结果}for(int i = lenb; i < lena; ++i){//a 的高位直接拿下来res[i] = a[lena-i-1]-'0';}}else{//如果a < bfor(int i = 0; i < lena; ++i){res[i] = b[lenb-i-1]-a[lena-i-1];}for(int i = lena; i < lenb; ++i){//b的高位直接放下来res[i] = b[lenb-i-1]-'0';}}for(int i = 0; i < max_len; ++i){//对结果进行借位处理if(res[i] < 0){res[i] += 10;res[i+1] -= 1;}}string r = "";if(!flag) //确定结果符号 r += "-";int k; for(k = max_len-1; k >= 0; --k){ //过滤掉前缀 0 if(res[k] != 0) break;}if(k == -1){ //当两个数之差 为 0 时候 保存 0值 return r += '0';//差值为0}for(; k >= 0; --k){//结果不为0时候记录结果r += res[k]+'0';}return r;}string bigAdd(const string a,const string b){int lena = a.size();int lenb = b.size();int lensum = lena > lenb ? lena+1 : lenb+1;vector<char> res;res.resize(lensum); for(int i = 0,j = 0; i < lena && j < lenb; ++i,++j){res[i] = a[lena-i-1]-'0' + b[lenb-i-1]-'0';}if(lena > lenb){for(int i = lenb; i < lena; ++i){res[i] = a[lena-i-1]-'0';}}else if(lenb > lena){for(int i = lena; i < lenb; ++i){res[i] = b[lenb-i-1]-'0';}}for(int i = 0; i < lensum-1; ++i){if(res[i] > 9){int t = res[i]/10;res[i] = res[i]%10;res[i+1] += t;}}string r = "";if(res[lensum-1]){//判断是否进位到最高位r += res[lensum-1]+'0';}for(int i = lensum-2; i >= 0; --i){//这里是lensum-2 r += res[i]+'0';} return r; }string getSum(const string a,const string b){string res;if(a[0] == b[0] && a[0] == '-'){//两个数都是负数res = "-" + bigAdd(a.substr(1),b.substr(1));}if(a[0] != '-' && b[0] != '-'){//都为正数res = bigAdd(a,b);}if((a[0]=='-'&&b[0]!='-') || (a[0] != '-' && b[0] =='-')){//异号相加 转化为 减法运算if(a[0] == '-'){res = bigSub(b,a.substr(1));}else{res = bigSub(a,b.substr(1));}}return res; }
int main(){string a, b;cin >> a >> b;//cout << bigSub(a,b);cout << getSum(a,b);return 0;}
这篇关于51nod 1005: 大数加法(含符号)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!