Given two non-negative integers, num1 and num2 represented as strings, return the sum of num1 and num2 as a string.
BigInteger in Java).StringBuilder and ensure you handle the carry after processing all digits.StringBuilder to get the final result.public class AddStrings {
public String addStrings(String num1, String num2) {
StringBuilder result = new StringBuilder();
int i = num1.length() - 1, j = num2.length() - 1, carry = 0;
while (i >= 0 || j >= 0 || carry > 0) {
int digit1 = i >= 0 ? num1.charAt(i) - '0' : 0;
int digit2 = j >= 0 ? num2.charAt(j) - '0' : 0;
int sum = digit1 + digit2 + carry;
carry = sum / 10;
result.append(sum % 10);
i--;
j--;
}
return result.reverse().toString();
}
public static void main(String[] args) {
AddStrings solution = new AddStrings();
System.out.println(solution.addStrings("123", "456")); // 579
System.out.println(solution.addStrings("456", "77")); // 533
System.out.println(solution.addStrings("0", "0")); // 0
}
}
num1 and (M) is the length of num2. Each digit is processed once.This strategy ensures that we add the strings without converting them to integers directly, thus handling very large numbers.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?