Java Solution. 32ms

• ``````public class Solution {
public String addStrings(String num1, String num2) {
if(num1.length()==0) return num2;
if(num2.length()==0) return num1;
StringBuilder sb = new StringBuilder();
if(num2.length()>num1.length()){
// make sure num1 is the longer string
String temp = num2;
num2 = num1;
num1 = temp;
}
int l1 = num1.length()-1;
int l2 = num2.length()-1;
int carry = 0;
for (int i=0;i<=l2;i++){
int sum = (num1.charAt(l1-i)-'0')+(num2.charAt(l2-i)-'0')+carry;
if (sum>=10) {
sb.insert(0,(sum-10));
carry = 1;
}else{
sb.insert(0,sum);
carry=0;
}
}
if(carry==0&&(l1-l2)>0){
for(int i=l1-l2-1;i>=0;i--){
sb.insert(0,num1.charAt(i));
}
}
if(carry==1&&((l1-l2)==0)){
sb.insert(0,"1");
carry=0;
}
if(carry==1&&((l1-l2)>0)){
for(int i=l1-l2-1;i>=0;i--){
int sum = carry+(num1.charAt(i)-'0');
if(sum>=10){
sb.insert(0,(sum-10));
carry = 1;
} else {
sb.insert(0,sum);
carry=0;
}
}
}
if (carry==1) sb.insert(0,"1");
return sb.toString();
}
}
``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.