Directory link:
Lituo Programming Problems - Summary of Solutions_Share+Records-CSDN Blog
GitHub synchronous brushing project:
https://github.com/September26/java-algorithms
Link to the original title: Likou
describe:
Given the sum of two nonnegative integers as strings num1
, num2
compute their sum and return it as a string.
You cannot use any of the built-in libraries for handling large integers (for example BigInteger
), nor can you directly convert input strings to integer form.
Example 1:
Input: num1 = "11", num2 = "123" Output: "134"
Example 2:
Input: num1 = "456", num2 = "77" Output: "533"
Example 3:
Input: num1 = "0", num2 = "0" Output: "0"
hint:
1 <= num1.length, num2.length <= 104
num1
andnum2
both contain numbers only0-9
num1
andnum2
neither contain any leading zeros
Problem-solving ideas:
/**
* 415. String addition
* Given two non-negative integers num1 and num2 in the form of strings, calculate their sum and return it as a string.
* You cannot use any built-in library for handling large integers (such as BigInteger), nor can you directly convert the input string to integer form.
*
* Problem-solving ideas:
* Convert num1 and num2 to an array of char type, then take the value of each bit from right to left, add the two numbers and sum, if the sum is greater than 10, carry, otherwise add the sum directly.
* The end condition is that both arrays are traversed and the carry is false.
*/
code:
class Solution415
{
public:
string addStrings(string num1, string num2)
{
std::vector<char> c1(num1.begin(), num1.end());
std::vector<char> c2(num2.begin(), num2.end());
bool isJin = false;
int i = 0;
string str = "";
while (i < num1.size() || i < num2.size() || isJin)
{
int value1 = 0;
int value2 = 0;
int index = num1.size() - i - 1;
if (index >= 0)
{
value1 = c1[index] - '0';
}
index = num2.size() - i - 1;
if (index >= 0)
{
value2 = c2[index] - '0';
}
value1 = value1 + value2;
if (isJin)
{
value1++;
isJin = false;
}
if (value1 > 10)
{
value1 -= 10;
isJin = true;
}
str.insert(0, to_string(value1));
i++;
}
return str;
}
};