#include <iostream> #include <string> #include <deque> using std::cout; using std::endl; using std::deque; using std::string; class Solution { public: string bigNumAdd(const string & a,const string & b){ //-------------------- //a,b格式: //1)a,b非空且都是数字字符 //2)a,b不带正负符号 //3)a,b没有前导0 //如2342332,23300,0合法 //+2322,-23423,0243不合法 //由调用函数保证a,b的格式 //-------------------- int n1 = a.size(); int n2 = b.size(); int len = std::max(n1,n2); deque<char> result(len,0); char carry = 0;//进位 int i = n1 - 1; int j = n2 - 1; int k = len - 1; //处理相重叠部分 for(;i >=0 && j >=0;--i,--j,--k){ result[k] = carry + toVal(a[i]) + toVal(b[j]); carry = result[k] / 10; result[k] %= 10; } //处理剩余部分 while(i >= 0){ result[k] = carry + toVal(a[i]); carry = result[k] / 10; result[k] %= 10; --i; --k; } while(j >= 0){ result[k] = carry + toVal(b[j]); carry = result[k] / 10; result[k] %= 10; --j; --k; } //处理最后的进位 while(carry > 0){ result.push_front(carry % 10); carry /= 10; } //将result的结果转化成string返回 string resultStr(result.size(),'0'); for(size_t i = 0;i < result.size();++i){ resultStr[i] += result[i]; } return resultStr; } private: inline char toVal(char c){//数字字符转成其代表的值 return c-'0'; } bool isGE(const string & a,const string & b){ if(a.size() != b.size()){ return a.size() > b.size(); } return a >= b; } }; int main(){ Solution sl; string a = "123456789"; string b = "999999999"; cout << sl.bigNumAdd(a,b) << endl; }
大整数加法
最新推荐文章于 2024-07-11 16:10:03 发布
773

被折叠的 条评论
为什么被折叠?



