题目来源: https://leetcode.com/problems/add-strings/
问题描述: 计算字符串num1和num2的和值字符串,num1和num2只包含数字,不允许将字符串转化为整型再计算
举例说明:
输入num1 | 输入num2 | 结果 | 解释 |
---|---|---|---|
'10' | '20' | '30' | 10 + 20 = 30 |
'12' | '13' | '25' | 12 + 13 = 25 |
解决方案
- 将字符串转化为字符后进行减法运算,时间复杂度Ο(n)
public String addStrings(String num1, String num2) {
StringBuilder sb = new StringBuilder();
int i = num1.length() - 1;
int j = num2.length() - 1;
int carry = 0;
while (i >= 0 || j >= 0) {
int sum = carry;
if (i >= 0) {
sum += num1.charAt(i) - '0';
i--;
}
if (j >= 0) {
sum += num2.charAt(j) - '0';
j--;
}
carry = sum / 10;
sb.append(sum % 10);
}
if (carry == 1) {
sb.append(carry);
}
return sb.reverse().toString();
}