题解 | #高精度整数加法#
高精度整数加法
http://www.nowcoder.com/practice/49e772ab08994a96980f9618892e55b6
我的思路很简单就是逐位相加, 特别注意处理进位,但是、但是时间貌似好久,我后期得想办法优化啊
using namespace std;
int main()
{
string str1, str2, maxLenStr, minLenStr;
int pos, i, j, tmp;
while(cin >> str1 >> str2) {
if (str1.length() >= str2.length()) {
maxLenStr = str1;
minLenStr = str2;
} else {
maxLenStr = str2;
minLenStr = str1;
}
j = maxLenStr.length() - 1;
pos = 0;
//短数字加完
for (i = minLenStr.length() - 1; i >= 0; i--) {
tmp = int(minLenStr[i] - '0') + int (maxLenStr[j] - '0') + pos;
if (tmp >= 10) {
pos = tmp / 10;
maxLenStr[j] = char(tmp - pos * 10 + '0');
} else{
maxLenStr[j] = char(tmp + '0');
pos = 0;
}
j--;
}
//处理进位
while (pos > 0) {
if (j < 0) {
maxLenStr = char(pos + '0') + maxLenStr;
pos = 0;
} else {
tmp = int (maxLenStr[j] - '0') + pos;
if (tmp >= 10) {
pos = tmp / 10;
maxLenStr[j] = char(tmp - pos * 10 + '0');
} else{
maxLenStr[j] = char(tmp + '0');
pos = 0;
}
j--;
}
}
cout << maxLenStr << endl;
}
}