高精度问题
string&insert(size_t pos, size_t count,char ch);
表格
| 参数 |
代码中的值 |
具体含义 |
pos |
0 |
插入位置:从字符串 b 的第 0 个位置(开头) 开始插入 |
count |
a.length() - b.length() |
插入数量:需要补充的 ‘0’ 的个数(等于 a 和 b 的长度差) |
ch |
'0' |
插入字符:要插入的是字符 ‘0’(不是数字 0) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| #include <bits/stdc++.h>
using namespace std;
string add(string a,string b){ if(a.length()<b.length()) a.swap(b); string result(a.length(),0); b.insert(0,a.length()-b.length(),'0'); int carry=0; for(int i=a.length()-1;i>=0;i--){ int sum=(a[i]-'0')+(b[i]-'0')+carry; result[i]=sum%10+48; carry=sum/10; } if(carry!=0){ result.insert(result.begin(),carry+48); } return result; }
int main () { string a,b; while(cin>>a>>b){ cout<<add(a,b)<<endl; } }
|