




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.
1public class AddStrings {
2    public static void main(String[] args) {
3        String num1 = "456";
4        String num2 = "77";
5        System.out.println(addStrings(num1, num2));
6    }
7
8    public static String addStrings(String num1, String num2) {
9        StringBuilder result = new StringBuilder();
10        int carry = 0, i = num1.length() - 1, j = num2.length() - 1;
11
12        while (i >= 0 || j >= 0 || carry != 0) {
13            int x = (i >= 0) ? num1.charAt(i) - '0' : 0;
14            int y = (j >= 0) ? num2.charAt(j) - '0' : 0;
15            int sum = x + y + carry;
16
17            result.append(sum % 10);
18            carry = sum / 10;
19
20            i--; j--;
21        }
22
23        return result.reverse().toString();
24    }
25}This Java implementation uses a StringBuilder to efficiently build the result string. By reversing the order of addition (from last digit to first), we handle carries and fill the final result string in one pass, reversing it at the end to ensure correct digit placement.
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.