
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#include <string>
using namespace std;
string addStrings(string num1, string num2) {
int i = num1.size() - 1, j = num2.size() - 1;
int carry = 0;
string result = "";
while (i >= 0 || j >= 0 || carry) {
int x = i >= 0 ? num1[i--] - '0' : 0;
int y = j >= 0 ? num2[j--] - '0' : 0;
int sum = x + y + carry;
result = to_string(sum % 10) + result;
carry = sum / 10;
}
return result;
}
int main() {
cout << addStrings("456", "77") << endl;
return 0;
}This C++ approach uses string concatenation from front, conveniently managing variable lengths and carryovers through reversing pointers from string ends. The carry is accounted for through intermediate addition, and digit concatenation provides the final sum without additional reversals, keeping operations simple and direct.