题目:传送门
解答:大数(范围超过可表示精度)加法,C++没有java的相应的大数类,直接用字符串模拟。几个小trick:
#include <iostream> #include <string> #include <stdio.h> #include <stdlib.h> #include <vector> using namespace std; int main() { int t; cin>>t; string pa, pb, a, b, c, tmp; vector<char> save; int jinwei, sum; for (int k = 0; k < t; k++) { cin>>pa>>pb; save.clear(); c.clear(); // 重置顺序!但是保留原先的数值 if(pa.size() < pb.size()) { a = pb; b = pa; } else { a = pa; b = pb; } int maxlen = a.size(); int minlen = b.size(); sum = 0; jinwei = 0; int i = maxlen; int j = minlen; while((i--) && (j--)) { sum = a[i] - '0' + b[j] - '0'; if(jinwei) sum++; if(sum > 9) { jinwei = 1; } else { jinwei = 0; } save.push_back((char)(sum % 10 + '0')); } /*if ((maxlen - minlen) != 0) {*/ for (i = (maxlen - minlen - 1); i >= 0 ; i--) { sum = a[i] - '0'; if(jinwei) sum++; if(sum > 9) { jinwei = 1; } else { jinwei = 0; } save.push_back((char)(sum % 10 + '0')); } //} if(jinwei) { save.push_back('1'); } for (int i = save.size() - 1; i>=0 ; i--) { c = c + save[i]; } printf("Case %d:\n", k+1); cout<<pa<<" + "<<pb<<" = "<<c<<endl; if (k != t - 1) { cout<<endl; } } return 0; }
原文地址:http://blog.csdn.net/ironyoung/article/details/45420161