415. Add Strings (Easy)
https://leetcode.com/problems/add-strings/
Given two non-negative integers num1
and num2
represented as string, return the sum of num1
and num2
.
Note:
- The length of both
num1
andnum2
is < 5100. - Both
num1
andnum2
contains only digits0-9
. - Both
num1
andnum2
does not contain any leading zero. - You must not use any built-in BigInteger library or convert the inputs to integer directly.
Solutions
class Solution {
public String addStrings(String num1, String num2) {
if (num1 == null) {
return num2;
}
if (num2 == null) {
return num1;
}
String ans = "";
int len1 = num1.length();
int len2 = num2.length();
int carrier = 0;
for (int i = 0; i < len1 || i < len2; i++) {
int x = 0;
int y = 0;
if (i < len1) {
x = num1.charAt(len1 - i - 1) - '0';
}
if (i < len2) {
y = num2.charAt(len2 - i - 1) - '0';
}
int remainder = (x + y + carrier) % 10;
ans = remainder + ans;
carrier = (x + y + carrier) / 10;
}
if (carrier != 0) {
ans = carrier + ans;
}
return ans;
}
}