题目地址:https://leetcode.com/problems/add-strings/
Given two non-negative numbers num1 and num2 represented as string, return the sum of num1 and num2.
Note:
- The length of both num1 and num2 is < 5100.
- Both num1 and num2 contains only digits 0-9.
- Both num1 and num2 does not contain any leading zero.
- You must not use any built-in BigInteger library or convert the inputs to integer directly.
题目要将两个数字字符串转换为数字,然后相加,得出结果,再转换为字符串。题目第四条说的很明确,不能用内置的转换方法,要是可以,那不就太简单了么。
题目本身没啥难度,关键是进位处理,这一点都考虑到了,也就没啥问题了。
public class AddStrings {
public String addStrings(String num1, String num2) {
StringBuilder result = new StringBuilder("");
//进位标记
boolean carry = false;
for (int i = num1.length() - 1, j = num2.length() - 1 ; i >= 0 && j >= 0; i--, j--) {
int t = 0;
if (carry)
t = num1.charAt(i) - '0' + num2.charAt(j) - '0' + 1;
else
t = num1.charAt(i) - '0' + num2.charAt(j) - '0';
if (t >= 10)
carry = true;
else
carry = false;
if (carry)
result.insert(0, String.valueOf((char)('0' + (t-10))));
else
result.insert(0, String.valueOf((char)('0' + t)));
}
// 不等长的时候,余下的位的计算,注意这里也有可能产生进位。
if (num1.length() > num2.length()) {
for (int i = num1.length() - num2.length() - 1; i >= 0; i--) {
int t = 0;
if (carry)
t = num1.charAt(i) - '0' + 1;
else
t = num1.charAt(i) - '0';
if (t >= 10)
carry = true;
else
carry = false;
if (carry)
result.insert(0, String.valueOf((char)('0' + (t-10))));
else
result.insert(0, String.valueOf((char)('0' + t)));
}
}
if (num2.length() > num1.length()) {
for (int i = num2.length() - num1.length() - 1; i >= 0; i--) {
int t = 0;
if (carry)
t = num2.charAt(i) - '0' + 1;
else
t = num2.charAt(i) - '0';
if (t >= 10)
carry = true;
else
carry = false;
if (carry)
result.insert(0, String.valueOf((char)('0' + (t-10))));
else
result.insert(0, String.valueOf((char)('0' + t)));
}
}
if (carry)
result.insert(0, '1');
return result.toString();
}
public static void main(String[] args) {
AddStrings addStrings = new AddStrings();
System.out.println(addStrings.addStrings("999929", "72"));
}
}
时间复杂度为:O(max{m, n}),其中m和n分别是两个字符串的长度。