LeetCode#415. 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.

补充说明:

这个题目的要求是:给定你两个字符串,然后需要把它们两个相加,得到它的值,值同样为字符串。但这里有个要求,就是不允许使用相关的库将输入转换为integer(整数)。

方案分析

  1. 这个题目就是典型的字符串转换数字的方式,传统的c或者java程序肯定想到的是ascii码的加减形式实现。
  2. 这里使用python,python的特性就是可以将字符串转换为list,然后逐位相加,生成list,最后将这个list转换为字符串即可。

python实现

class Solution(object):
    def addStrings(self, num1, num2):
        """
        :type num1: str
        :type num2: str
        :rtype: str
        """
        def _convertInter(num):
            return ord(num) - ord('0')

        # 将两个字符串逆序后,转换为list,这里题目有要求,不能使用库函数直接把string转换为int,需要我们自己实现一个字符串转换数字的函数。
        num1, num2 = list(map(_convertInter, num1[::-1])), list(map(int, num2[::-1]))

        # 如果num2的长度 大于 num1,交换它们的顺序。
        if len(num1)

方案分析2

  1. 在leetcode社区,看到有人使用了itertools中的高级方法——izip_longest,这个函数能将两个字符串转换为每位对应的tuple,不够的可以补齐你指定的字符,这个方法简直太好用了。话不多说,贴出他人的代码。

python实现2

from itertools import izip_longest
class Solution(object):
    def addStrings(self, num1, num2):
        res, c = "", 0
        for (x, y) in izip_longest(num1[::-1], num2[::-1], fillvalue='0'):
            s = (int(x) + int(y) + c)
            d, c = s % 10, int(s / 10)
            res = str(d) + res

        if c > 0: res = str(c) + res

        return res

你可能感兴趣的:(LeetCode#415. Add Strings)