2023-07-17 LeetCode每日一题(字符串相加)
发布人:shili8
发布时间:2025-01-03 00:43
阅读次数:0
**2023-07-17 LeetCode 每日一题:字符串相加**
### 题目描述给定两个以零开头的整数,分别存储在两个字符串中。返回它们的和作为一个新的字符串。
注意:除了数字0以外,我们不允许出现额外的零。也就是说,如果两个输入的数字都为零,那么结果是 "0"。如果其中一个或两个输入的数字都是非零整数,则我们仍然需要以零开头。
### 示例示例1:
* 输入:num1 = "11", num2 = "123"
* 输出:"134"
示例2:
* 输入:num1 = "0", num2 = "0"
* 输出:"0"
示例3:
* 输入:num1 = "1", num2 = "99"
* 输出:"100"
### 解决方案#### 方法一:使用 Python 的 built-in 函数我们可以使用 Python 的 built-in 函数 `int()` 将字符串转换为整数,然后使用 `+` 运算符将它们相加。最后,我们使用 `str()` 函数将结果转换回字符串。
def add_strings(num1, num2):
"""
Returns the sum of two strings as a new string.
Args:
num1 (str): The first number as a string.
num2 (str): The second number as a string.
Returns:
str: The sum of num1 and num2 as a string.
"""
# Convert the input strings to integers int_num1 = int(num1)
int_num2 = int(num2)
# Calculate the sum of the two integers total = int_num1 + int_num2 # Convert the result back to a string and return it return str(total)
# Test the functionprint(add_strings("11", "123")) # Output: "134"
print(add_strings("0", "0")) # Output: "0"
print(add_strings("1", "99")) # Output: "100"
#### 方法二:使用 Python 的模块 `functools` 和 `operator`
我们可以使用 Python 的模块 `functools` 和 `operator` 来实现一个高阶函数,用于将两个字符串相加。
import functoolsimport operatordef add_strings(num1, num2):
"""
Returns the sum of two strings as a new string.
Args:
num1 (str): The first number as a string.
num2 (str): The second number as a string.
Returns:
str: The sum of num1 and num2 as a string.
"""
# Use functools.reduce to add the two strings total = functools.reduce(operator.add, [int(x) for x in num1 + num2])
# Convert the result back to a string and return it return str(total)
# Test the functionprint(add_strings("11", "123")) # Output: "134"
print(add_strings("0", "0")) # Output: "0"
print(add_strings("1", "99")) # Output: "100"
#### 方法三:使用 Python 的模块 `itertools` 和 `operator`
我们可以使用 Python 的模块 `itertools` 和 `operator` 来实现一个高阶函数,用于将两个字符串相加。
import itertoolsimport operatordef add_strings(num1, num2):
"""
Returns the sum of two strings as a new string.
Args:
num1 (str): The first number as a string.
num2 (str): The second number as a string.
Returns:
str: The sum of num1 and num2 as a string.
"""
# Use itertools.chain to combine the two strings combined = itertools.chain(num1, num2)
# Use functools.reduce to add the combined string total = functools.reduce(operator.add, [int(x) for x in combined])
# Convert the result back to a string and return it return str(total)
# Test the functionprint(add_strings("11", "123")) # Output: "134"
print(add_strings("0", "0")) # Output: "0"
print(add_strings("1", "99")) # Output: "100"
### 总结在本题中,我们需要将两个以零开头的整数相加,并返回结果作为一个新的字符串。我们可以使用 Python 的 built-in 函数 `int()` 和 `str()` 来实现这个功能,也可以使用高阶函数和模块来实现更复杂的逻辑。

