描述:
題目描述:請設計一個算法完成兩個超長正整數的加法。
要求實現函數:
void AddLongInteger(char * pcAddend, char * pcAugend, char * pcAddResult);
輸入參數:
char * pcAddend:加數
char * pcAugend:被加數
char * pcAddResult:加法結果
返回值:無
運行時間限制: 1 Sec
內存限制: 128 MByte
輸入:
兩個超長正整數的字符串
輸出:
相加後結果的字符串
樣例輸入:
123456789123456789 123456789123456789
樣例輸出:
246913578246913578ios
測試不經過,發出來看看問題在哪裏。c++
// // 超長正整數相加.cpp // temptest // // Created by 彭威 on 15/8/1. // Copyright © 2015年 biophy.nju.edu.cn. All rights reserved. // #include <iostream> #include <algorithm> #include <string> using namespace std; class BigNumber { string num; bool reverse_flg; public: BigNumber(char *str):num(str){} BigNumber(){}; friend istream& operator>>(istream& in,BigNumber& p){ in>>p.num; return in; } friend ostream& operator<<(ostream& out,const BigNumber& p){ if (p.reverse_flg) { //for (auto iter = p.num.rbegin(); iter != p.num.rend(); iter++) { //only for c++11 for (string::const_iterator iter = p.num.end()-1;iter >= p.num.begin();--iter ){ out<<*iter; } }else{ out<<p.num; } return out; } friend const BigNumber operator+(const BigNumber& p1,const BigNumber& p2){ BigNumber p; size_t len = max(p1.length(), p2.length()); char plus=0; p.reverse_flg = true; for (size_t i =0; i < len; i++) { char x = p1[i] + p2[i] + plus - 2 * '0'; plus = x / 10; x = x % 10 + '0'; p.num.push_back(x); } if (plus) { p.num.push_back(plus+'0'); plus = 0; } return p; } const size_t length() const{ return num.length(); } const char operator[](size_t n)const { if (n >= num.length()) { return '0'; } if (reverse_flg) { return num[n]; }else{ return num[num.length()-n-1]; } } }; int main(int argc,const char* argv[]){ BigNumber a,b; cin>>a>>b; cout<<a+b<<endl; return 0; }