Topic link
Title description:
Given two non-negative integers num1 and num2 in the form of strings, calculate their sum.
note:
The length of
num1 and num2 are both less than 5100. Both num1 and num2 only contain the numbers 0-9.
Neither num1 nor num2 contain any leading zeros.
You cannot use any built-in BigInteger library, nor can you directly convert the input string into an integer form.
Problem-solving ideas
From num1
and num2
at the end of traversing, bit by bit added. There are four main aspects to consider:
- Carry calculation:
carry = temp / 10
represents the result of the carry after the current bit is added - Calculate the current
temp = (n1 + n2 + carry) % 10
position: . Then add the result to theresult
tail for
The judgment condition in the loop is addedcarry != 0
to judge whether the addition of the highest bit overflows- If
i
,j
have run head, for example131 + 92
, then to the correspondingn1
orn2
set0
When the loop is completed, result
the order we found is reversed, and we need reverse
to output it later.
Code
class Solution {
public:
string addStrings(string num1, string num2) {
string result = "";
int carry = 0;
for(int i = num1.size() - 1, j = num2.size() - 1;
i >= 0 || j >= 0 || carry != 0;
i--, j--){
int n1 = i < 0 ? 0 : num1[i] - '0';
int n2 = j < 0 ? 0 : num2[j] - '0';
int temp = (n1 + n2 + carry) % 10;
result += to_string(temp);
carry = (n1 + n2 + carry) / 10;
}
reverse(result.begin(), result.end());
return result;
}
};
If there are mistakes or not rigorous, please correct me, thank you very much.
My blog: http://breadhunter.gitee.io