




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.
1using System;
2using System.Text;
3
4public class AddStrings {
5    public static void Main(string[] args) {
6        Console.WriteLine(AddStrings("0", "0"));
7    }
8
9    public static string AddStrings(string num1, string num2) {
10        var result = new StringBuilder();
11        int carry = 0, i = num1.Length - 1, j = num2.Length - 1;
12
13        while (i >= 0 || j >= 0 || carry != 0) {
14            int x = (i >= 0) ? num1[i] - '0' : 0;
15            int y = (j >= 0) ? num2[j] - '0' : 0;
16
17            int sum = x + y + carry;
18            result.Append(sum % 10);
19            carry = sum / 10;
20
21            i--;
22            j--;
23        }
24
25        char[] resultArray = result.ToString().ToCharArray();
26        Array.Reverse(resultArray);
27        return new string(resultArray);
28    }
29}This C# solution involves adding digits from the string ends using a loop, similar to manual addition, including carry management. The result is built using a StringBuilder and reversed before returning to present the correct order.
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.
1
This C implementation utilizes dynamic memory allocation to handle the expected length of the result string. By manipulating pointers, the implementation skillfully confines carry operations within the loop. The function returns a pointer to the correct start of the result string after adjusting for any leading zeros produced by initial carry operations.