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.

描述

给定两个字符串形式的非负整数 num1 和num2 ,计算它们的和。

注意:

num1 和num2 的长度都小于 5100.
num1 和num2 都只包含数字 0-9.
num1 和num2 都不包含任何前导零。
你不能使用任何內建 BigInteger 库, 也不能直接将输入的字符串转换为整数形式。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/probl...
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路

  • 实现一个 str 转换 int 的函数,然后求和。
  • 将求到的和转换为 str 类型
# -*- coding: utf-8 -*-
# @Author:             何睿
# @Create Date:        2019-10-14 19:42:33
# @Last Modified by:   何睿
# @Last Modified time: 2019-10-14 19:47:43


class Solution:
    def addStrings(self, num1: str, num2: str) -> str:
        return str(self._int(num1) + self._int(num2))

    def _int(self, num):
        res = 0
        cnt = 1
        for s in num[::-1]:
            res += cnt * (ord(s) - ord('0'))
            cnt *= 10
        return res

源代码文件在 这里
©本文首发于 何睿的博客 ,欢迎转载,转载需保留 文章来源 ,作者信息和本声明.


何睿
0 声望2 粉丝

热爱生活,关注互联网