- 题目:两个整数相加(字符串的形式)
- 思路:对应位相加,然后考虑进位(与LeetCode#67. Add Binary基本一样)
- 难度:Easy
- 代码:
public class Solution {
public String addStrings(String num1, String num2) {
int len1 = num1.length();
int len2 = num2.length();
if(len1 == 0){
return num2;
}
if(len2 == 0){
return num1;
}
int i = len1 - 1;
int j = len2 - 1;
int sum = 0;
int carry = 0;
StringBuilder sb = new StringBuilder();
while(i >= 0 || j >= 0){
sum = carry;
if(i >= 0) sum += num1.charAt(i--) - '0';
if(j >= 0) sum += num2.charAt(j--) - '0';
sb.append(sum%10);
carry = sum/10;
}
if(carry != 0) sb.append(carry);
return sb.reverse().toString();
}
}