Leetcode 415. 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.
class Solution {
public String addStrings(String num1, String num2) {
if(num1.length() < num2.length()) { // 让num1始终为较长的那个字符串
String temp = num1;
num1 = num2;
num2 = temp;
}
int len1 = num1.length();
int len2 = num2.length();
num1 = new StringBuilder(num1).reverse().toString(); //逆序
num2 = new StringBuilder(num2).reverse().toString();
StringBuilder sb = new StringBuilder();
int carry = 0; // 进位
for(int i = 0 ; i < len1; i++) {
int a = num1.charAt(i) - '0';
int b = (i < len2) ? num2.charAt(i) - '0' : 0;
int r = a + b + carry; // 别忘了加上进位
if(r >= 10) {
r %= 10;
carry = 1;
}else {
carry = 0;
}
sb.append(r);
}
if(carry == 1) sb.append(carry); // 如果最后还有进位,别忘了加上
return sb.reverse().toString();
}
}