LeetCode 415. Add Strings

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

v2-8e551ef66ac7e7aa24146c36b1d6aedc_1440w.jpg

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/problems/add-strings

著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。


思路



  • 实现一个 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

源代码文件在 这里


目录
相关文章
|
8月前
Leetcode 623. Add One Row to Tree
题目很简单,在树的第d层加一层,值为v。递归增加一层就好了。代码如下
30 0
|
10月前
|
存储 C++ Python
LeetCode刷题---Add Two Numbers(一)
LeetCode刷题---Add Two Numbers(一)
|
存储 算法 安全
LeetCode - #2 Add Two Numbers
我们社区从本期开始会将顾毅(Netflix 增长黑客,《iOS 面试之道》作者,ACE 职业健身教练。)的 Swift 算法题题解整理为文字版以方便大家学习与阅读。 不积跬步,无以至千里;不积小流,无以成江海,Swift社区 伴你前行。
LeetCode - #2 Add Two Numbers
LeetCode 258. Add Digits
给定一个非负整数 num,反复将各个位上的数字相加,直到结果为一位数。
60 0
LeetCode 258. Add Digits
LeetCode 241. Different Ways to Add Parentheses
给定一个含有数字和运算符的字符串,为表达式添加括号,改变其运算优先级以求出不同的结果。你需要给出所有可能的组合的结果。有效的运算符号包含 +, - 以及 * 。
61 0
LeetCode 241. Different Ways to Add Parentheses
LeetCode 205. Isomorphic Strings
给定两个字符串 s 和 t,判断它们是否是同构的。 如果 s 中的字符可以被替换得到 t ,那么这两个字符串是同构的。 所有出现的字符都必须用另一个字符替换,同时保留字符的顺序。两个字符不能映射到同一个字符上,但字符可以映射自己本身。
60 0
LeetCode 205. Isomorphic Strings
LeetCode 67. Add Binary
给定两个二进制字符串,返回它们的总和(也是二进制字符串)。 输入字符串都是非空的,只包含字符1或0。
60 0
LeetCode 67. Add Binary
LeetCode 43. Multiply Strings
给定两个表示为字符串形式的非负整数num1和num2,返回num1和num2的乘积,也表示为字符串形式。
57 0
LeetCode 43. Multiply Strings
|
人工智能 算法
LeetCode 1347. 制造字母异位词的最小步骤数 Minimum Number of Steps to Make Two Strings Anagram
LeetCode 1347. 制造字母异位词的最小步骤数 Minimum Number of Steps to Make Two Strings Anagram
|
存储
Leetcode-Medium 2. Add Two Numbers
Leetcode-Medium 2. Add Two Numbers
59 0