AddStrings [source code]
public class AddStrings {
public String addStrings(String num1, String num2) {
char[] digits1 = num1.toCharArray(), digits2 = num2.toCharArray();
int len1 = num1.length(), len2 = num2.length();
int len = Math.max(len1, len2);
if (len == 0) return "";
int carry = 0;
String res = "";
for (int i = 0; i < len; i++) {
int index1 = len1 - 1 - i;
int index2 = len2 - 1 - i;
int digit1 = index1 >= 0 ? digits1[index1] - '0' : 0;
int digit2 = index2 >= 0 ? digits2[index2] - '0' : 0;
int sum = digit1 + digit2 + carry;
carry = sum / 10;
res = (sum % 10) + res;
}
return carry == 1 ? "1" + res : res;
}
public static void main(String[] args) {
AddStrings tester = new AddStrings();
System.out.println(tester.addStrings("123", "932"));
}
}
总体的思路是很简单, 就是按 bit 扫描; 一个小技巧就是loop var应该用从0开始, 然后里面再用 index 转换. 因为 len 本身是 len1和 len2的最大值, 所以从0开始向上增长, 在分段函数的分段逻辑的区分上更好处理一些.
这里要注意的是Integer.parseInt
这个这里不好用, 不能用在 char 上. 直接用类似字母的方法来处理, 一个减法就行了.
最后的速度倒是很差, 不知道为什么: 70(10).
Problem Description
Given two non-negative integers 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.
Difficulty:Easy
Category:Algorithms
Acceptance:41.24%
Contributor: LeetCode
Companies
google airbnb
Related Topics
math
Similar Questions
Add Two Numbers Multiply Strings