从来就没有救世主  也不靠神仙皇帝  要创造人类的幸福  全靠我们自己  

超长数运算

 

1. 两超长整数相加

  两个数先用字符串存储(C++可用string,然后用cin输入),从后往前,每次各取一个做加法,记下和(用栈)和进位值;下一次再取做加法时要加上进位......。一个字符串取完了,另一个没取完,则没取完的字符串继续加进位。

string x,y;
cin>>x>>y;
stack<int> tmp;
int i = x.size()-1;
int j = y.size()-1;
int p = 0; //进位
while(i>=0 && j>=0) {
    int t = x[i]-'0'+y[j]-'0'+p;
    tmp.push(t%10);
    p = t/10;
    i--;
    j--;
}
while(i>=0) {  //i和j肯定最多只有一个没用完
    int t = x[i]-'0'+p;
    tmp.push(t%10);
    p = t/10;
    i--;
}
while(j>=0) {
    int t = y[j]-'0'+p;
    tmp.push(t%10);
    p = t/10;
    j--;
}
if(p>0) { //最后的进位不能忘记
    tmp.push(p);
}
while(!tmp.empty()) {
    cout<<tmp.top();
    tmp.pop();
}
cout<<endl;

 

posted @ 2020-04-17 12:04  T,X  阅读(192)  评论(0编辑  收藏  举报