415. Add Strings
- Total Accepted: 4311
- Total Submissions: 9894
- Difficulty: Easy
- Contributors: Admin
Given two non-negative numbers 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.
Subscribe to see which companies asked this question
public class Solution {
public String addStrings(String num1, String num2) {
int len1=num1.length()-1;
int len2=num2.length()-1;
int carry=0;
StringBuilder out=new StringBuilder();
while(len1>=0||len2>=0){
int sum=carry;
if(len1>=0)
sum=sum+num1.charAt(len1--)-'0';
if(len2>=0)
sum=sum+num2.charAt(len2--)-'0';
out.append(sum%10);
carry=sum/10;
}
if(carry==1)
out.append(1);
return out.reverse().toString();
}
}