题解 | #高精度整数加法#
高精度整数加法
http://www.nowcoder.com/practice/49e772ab08994a96980f9618892e55b6
使用一个up变量来处理进位,初始时up=0;如果需要进位则up=1,不需要进位则up=0。
不需要进位时
a[i]+b[j]+up-'0';up=0;
需要进位时
a[i]+b[j]+up-'0'-10;up=1;处理长数据时不要忘记进位
/*HJ57高精度整数加法*/ #include<iostream> #include<algorithm> using namespace std; int main() { string a; string b; string c=""; int up=0; cin>>a>>b; int i=a.length()-1; int j=b.length()-1; while(i+1&&j+1) { if(a[i]+b[j]+up-'0'-'0'<=9) { c+=a[i]+b[j]+up-'0'; up=0; } else if(a[i]+b[j]+up-'0'-'0'>=10) { c+=a[i]+b[j]+up-'0'-10; up=1; if(i==0&&j==0) c+='1'; } i--; j--; } while(i>=0)//处理长数据 { if(a[i]+up-'0'<=9) { c+=a[i]+up; up=0; } else if(a[i]+up-'0'>=10) { c+=a[i]+up-10; up=1; } i--; } while(j>=0) { if(b[j]+up-'0'<=9) { c+=b[j]+up; up=0; } else if(b[j]+up-'0'>=10) { c+=b[j]+up-10; up=1; } j--; } reverse(c.begin(),c.end()); cout<<c<<endl; }
///*HJ57高精度整数加法*/ //#include<iostream> //using namespace std; //int main() //{ // string a; // string b; // long na=0,nb=0; // cin>>a>>b; // for(int i=0;i<a.length();i++) // { // na=na*10+a[i]-'0'; // } // for(int i=0;i<b.length();i++) // { // nb=nb*10+b[i]-'0'; // } // cout<<na<<endl; //}//超大数据会GG