Leetcode 415: Add Strings
Given two non-negative integers represented as strings, return the sum of these numbers as a string. The solution should avoid converting the strings to integers directly or using any built-in libraries for large integers.
Problem
Approach
Steps
Complexity
Input: The input consists of two strings num1 and num2, each representing a non-negative integer.
Example: For num1 = '5' and num2 = '789', the output is '794'.
Constraints:
• 1 <= num1.length, num2.length <= 10^4
• num1 and num2 consist of only digits.
• num1 and num2 don't have leading zeros except for '0'.
Output: Return the sum of the two numbers as a string.
Example: For num1 = '1234' and num2 = '876', the output is '2110'.
Constraints:
Goal: To add two large numbers represented as strings and return their sum as a string.
Steps:
• 1. Initialize a carry variable to 0 and an empty string to store the result.
• 2. Start from the rightmost digits of both strings and sum corresponding digits, including the carry from the previous sum.
• 3. If there are remaining digits in either string, continue summing them.
• 4. If there is any carry left after processing both strings, add it to the result.
• 5. Return the final result, ensuring that the digits are in the correct order.
Goal: The input strings represent non-negative integers and their lengths are between 1 and 10^4 characters.
Steps:
• 1 <= num1.length, num2.length <= 10^4
• num1 and num2 consist of only digits.
• num1 and num2 don't have leading zeros except for the zero itself.
Assumptions:
• The inputs are valid strings representing non-negative integers.
• Input: For num1 = '0' and num2 = '0', the output is '0'.
• Explanation: The sum of two zeros is zero, which is handled correctly by the algorithm.
Approach: Iterate through the strings from right to left, adding corresponding digits and managing carry to compute the sum of the two numbers.
Observations:
• We need to process the digits of both numbers one by one starting from the least significant digit.
• The strings may have different lengths, so we need to handle cases where one number has more digits than the other.
• Use two pointers to traverse both strings, and maintain a carry to handle overflow during addition.
Steps:
• 1. Initialize two indices i and j, starting from the last characters of num1 and num2 respectively.
• 2. Initialize a carry variable to store any carry-over during addition.
• 3. Loop through both strings, adding corresponding digits and updating the carry. If the sum of digits exceeds 9, set carry to 1.
• 4. After the loop, if there is a carry left, append it to the result.
• 5. Reverse the result string to get the correct sum in the right order.
Empty Inputs:
Large Inputs:
• If num1 or num2 is a very large number (e.g., 10^4 digits), the solution should still run efficiently.
Special Values:
• If either num1 or num2 is '0', the result should be the other number.
Constraints:
• Handle cases where the input strings have different lengths.
string addStrings(string num1, string num2) {
int carry=0,i=num1.length()-1,j=num2.length()-1;
string ans="";
while(i>=0||j>=0||carry>0){
if(i>=0){
carry=carry+num1[i]-'0';
i--;
}
if(j>=0){
carry=carry+num2[j]-'0';
j--;
}
ans += char(carry % 10 + '0');
carry =carry/ 10;
}
reverse(ans.begin(),ans.end());
return ans;
}
1 : Function Definition
string addStrings(string num1, string num2) {
Define the function `addStrings` which takes two strings, `num1` and `num2`, representing two non-negative integers, and returns their sum as a string.
2 : Variable Initialization
int carry=0,i=num1.length()-1,j=num2.length()-1;
Initialize the `carry` variable to 0, and set `i` and `j` to the last indices of `num1` and `num2`, respectively, to start adding from the rightmost digits.
3 : String Initialization
string ans="";
Initialize an empty string `ans` to store the result of the addition as the digits are processed.
4 : Loop Iteration
while(i>=0||j>=0||carry>0){
Start a `while` loop that continues as long as there are more digits to process or there is a carry left to add.
5 : Conditional Check
if(i>=0){
If there are still digits in `num1` (i.e., `i` is non-negative), process the current digit.
6 : Digit Processing
carry=carry+num1[i]-'0';
Add the current digit of `num1` (converted to an integer) to the `carry`.
7 : Index Decrement
i--;
Decrement the index `i` to move to the next left digit in `num1`.
8 : Conditional Check
}
End the `if` block for processing digits in `num1`.
9 : Conditional Check
if(j>=0){
If there are still digits in `num2` (i.e., `j` is non-negative), process the current digit.
10 : Digit Processing
carry=carry+num2[j]-'0';
Add the current digit of `num2` (converted to an integer) to the `carry`.
11 : Index Decrement
j--;
Decrement the index `j` to move to the next left digit in `num2`.
12 : Answer Construction
ans += char(carry % 10 + '0');
Append the current digit (obtained by taking the remainder of `carry` divided by 10) to the result string `ans`.
13 : Carry Update
carry =carry/ 10;
Update the `carry` by dividing it by 10 to ensure it contains only the carry-over for the next iteration.
14 : Reverse Operation
reverse(ans.begin(),ans.end());
Reverse the string `ans` to ensure the digits are in the correct order (since they were processed from right to left).
15 : Return Statement
return ans;
Return the final result string `ans` containing the sum of `num1` and `num2`.
Best Case: O(n)
Average Case: O(n)
Worst Case: O(n)
Description: The time complexity is O(n), where n is the maximum length of the two input strings, since we iterate through both strings once.
Best Case: O(n)
Worst Case: O(n)
Description: The space complexity is O(n), where n is the number of digits in the resulting sum, since we store the result in a string.
LeetCode Solutions Library / DSA Sheets / Course Catalog |
---|
comments powered by Disqus