【LeetCode】415. Add Strings 解题报告(Python)
作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/
[LeetCode]
题目地址:https://leetcode.com/problems/add-strings/
- Difficulty: Easy
题目描述
Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.
Note:
- The length of both
num1andnum2is< 5100. - Both
num1andnum2contains only digits0-9. - Both
num1andnum2does not contain any leading zero. - You must not use any built-in BigInteger library or convert the inputs to integer directly.
题目大意
不使用大整数的情况下,计算两个字符串表示的数字的和。
解题方法
我的想法出奇的直白,就是模仿小学学的两个数的相加,从末尾开始向前以次相加,注意进位,两个数的相加最多只能进1,因此只要一个boolean 型的量表示是否进位即可。
提前进行补零,这样能够使得两个数字长度一样,方便了计算。
class Solution(object):
def addStrings(self, num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
res = ""
carry = 0
M, N = len(num1), len(num2)
if M < N:
num1 = "0" * (N - M) + num1
else:
num2 = "0" * (M - N) + num2
N = max(M, N)
for i in range(N - 1, -1, -1):
add = int(num1[i]) + int(num2[i]) + carry
if add >= 10:
carry = 1
add -= 10
else:
carry = 0
res = str(add) + res
if carry:
res = "1" + res
return res
注意这几点:
- 两个数的位数保持一致才可。
- 加法的顺序是从个位向前
- 提前计算好两个数字的位数的差,否则在相加的时候会有变化。
Java代码如下。
public class Solution {
public String addStrings(String num1, String num2) {
int length = 0;
int sub = 0;
StringBuilder buffer1 = new StringBuilder(num1);
StringBuilder buffer2 = new StringBuilder(num2);
if (buffer1.length() > buffer2.length()) {
length = buffer1.length();
sub = buffer1.length() - buffer2.length();
} else {
length = buffer2.length();
sub = buffer2.length() - buffer1.length();
}
StringBuilder answer = new StringBuilder();
if (buffer1.length() > buffer2.length()) {
for (int i = 0; i < sub; i++) {
buffer2.insert(0, 0);
}
} else {
for (int i = 0; i < sub; i++) {
buffer1.insert(0, 0);
}
}
boolean up = false;
for (int i = length - 1; i >= 0; i--) {
int add = buffer1.charAt(i) - '0' + buffer2.charAt(i) - '0';
if (up) {
add++;
}
if (add >= 10) {
answer.insert(0, add - 10);
up = true;
} else {
answer.insert(0, add);
up = false;
}
if (i == 0 && up) {
answer.insert(0, 1);
}
}
return answer.toString();
}
}
AC: 38 ms
日期
2017 年 1 月 12 日
2018 年 11 月 19 日 —— 周一又开始了

浙公网安备 33010602011771号