Add Strings
- Total Accepted: 9009
- Total Submissions: 21652
- 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
Hide Similar Problems
java code:
public class Solution {
public static String addStrings(String num1, String num2) {
StringBuffer sb = new StringBuffer();
int i = num1.length() - 1, j = num2.length() - 1;
int a, b;
int c = 0;
int sum;
while (i >= 0 && j >= 0) {
a = num1.charAt(i) - '0';
b = num2.charAt(j) - '0';
sum = a + b + c;
sb.append(sum%10 +"");
c = sum/10;
i--;
j--;
}
while (i >= 0) {
sum = num1.charAt(i) - '0' + c;
sb.append(sum%10 + "");
c = sum/10;
i--;
}
while (j >= 0) {
sum = num2.charAt(j) - '0' + c;
sb.append(sum%10 + "");
c = sum/10;
j--;
}
if(c!=0){
sb.append(c+"");
}
sb.reverse();
return sb.toString();
}
}