LeetCode——Add Strings
LeetCode——Add Strings
Question
Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.
Note:
The length of both num1 and num2 is < 5100.
Both num1 and num2 contains only digits 0-9.
Both num1 and num2 does not contain any leading zero.
You must not use any built-in BigInteger library or convert the inputs to integer directly.
解题思路
这道题就是所谓的大整数加法操作,因为超过了计算机所能表示的范围数,所以用字符串表示,然后注意到就是,当两个长度不一样的时候,可以考虑往一个较短的字符串补‘0’,让两个字符串的长度保持一致。
具体实现
class Solution {
public:
// 大整数加法
string addStrings(string num1, string num2) {
string n1(num1.rbegin(), num1.rend());
string n2(num2.rbegin(), num2.rend());
int size1 = n1.length();
int size2 = n2.length();
if (size1 < size2) {
for (int i = 0; i < size2 - size1; i++) {
n1 += '0';
}
}
if (size1 > size2) {
for (int j = 0; j < size1 - size2; j++) {
n2 += '0';
}
}
int remainer = 0;
string str;
for (int i = 0; i < n1.length(); i++) {
int sum = n1[i] - 48 + n2[i] - 48 + remainer;
remainer = 0;
if (sum >= 10) {
sum = sum - 10;
remainer = 1;
}
char tmp = sum + 48;
str += tmp;
}
if (remainer == 1)
str += '1';
string str1(str.rbegin(), str.rend());
return str1;
}
};