
Sponsored
Sponsored
This approach involves reversing both input strings, then iterating through them to sum up each digit, similar to manual addition from the rightmost digit. This technique simplifies handling the carry over during addition.
Time Complexity: O(n), where n is the maximum length of num1 or num2.
Space Complexity: O(n), for the result array.
1def addStrings(num1: str, num2: str) -> str:
2 result = []
3 carry = 0
4 i, j = len(num1) - 1, len(num2) - 1
5
6 while i >= 0 or j >= 0 or carry:
7 x = int(num1[i]) if i >= 0 else 0
8 y = int(num2[j]) if j >= 0 else 0
9
10 sum_ = x + y + carry
11 result.append(str(sum_ % 10))
12 carry = sum_ // 10
13
14 i -= 1
15 j -= 1
16
17 return ''.join(reversed(result))
18
19# Example usage:
20print(addStrings("11", "123"))This Python implementation efficiently processes input strings num1 and num2 using a loop to sum digits from back to front, handling carries. The final sum is built using a list for ease of reversal and joined into a single string result.
This approach deploys two pointers, initially positioned at the end of each input string. We process each character one by one, moving the pointers from the rightmost end towards the start of each string. This allows us to readily manage the carry as we compute the sum step-by-step.
Time Complexity: O(n), where n is the maximum length of num1 or num2.
Space Complexity: O(n), necessary for the dynamically allocated result string.
1using System.Text;
public class AddStrings {
public static void Main(string[] args) {
Console.WriteLine(AddStrings("123", "87"));
}
public static string AddStrings(string num1, string num2) {
int i = num1.Length - 1, j = num2.Length - 1, carry = 0;
StringBuilder result = new StringBuilder();
while (i >= 0 || j >= 0 || carry > 0) {
int x = i >= 0 ? num1[i] - '0' : 0;
int y = j >= 0 ? num2[j] - '0' : 0;
int sum = x + y + carry;
result.Append(sum % 10);
carry = sum / 10;
i--;
j--;
}
char[] resultArray = result.ToString().ToCharArray();
Array.Reverse(resultArray);
return new string(resultArray);
}
}This C# solution follows a character-by-character approach to handle input strings. Through iterative addition and managed carries, it accumulates each digit's contribution into a StringBuilder, reversing afterward to align the digits in their correct order.