P1601 A+B Problem(高精) 找到规律,确定区间,迅速求解
// A+B problem string ADD(string a, string b) {
int la = a.length();
int lb = b.length();
int lc = max(la, lb) + 1;
string ans(lc, '0');
for (int i = 0; i <= lc - 1; i++) {
// 取值
//int x = 0, y = 0;
//if( i < la) x = a[i] - '0';
//if( i < lb) y = b[i] - '0';
// 简化版本
int x = i < la ? a[i] - '0' : 0;
int y = i < lb ? b[i] - '0' : 0;
// 关键语句
ans[i] = (ans[i] - '0' + x + y) % 10 + '0';
ans[i + 1] = (ans[i] - '0' + x + y) / 10 + '0';
}
// 判断最高位是不是0
string result = "";
for (int i = lc-1; i >=0 ; i--) {
if (i == lc - 1 && ans[i] == '0') continue;
else result += ans[i];
}
return result;
} 图解
// 更多信息可关注个人B站,分享资料https://space.bilibili.com/282213925