zoukankan      html  css  js  c++  java
  • 415.Add Strings

    Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.

    Note:

    1. The length of both num1 and num2 is < 5100.
    2. Both num1 and num2 contains only digits 0-9.
    3. Both num1 and num2 does not contain any leading zero.
    4. You must not use any built-in BigInteger library or convert the inputs to integer directly.

    Solution1:

    class Solution:
        def addStrings(self, num1, num2):
            """
            :type num1: str
            :type num2: str
            :rtype: str
            """
            return str(int(num1)+int(num2))
    

    python3的int是没有大小限制的。

    Solution2:

    class Solution:
        def addStrings(self, num1, num2):
            """
            :type num1: str
            :type num2: str
            :rtype: str
            """
            num1 = list(num1)[::-1]
            num2 = list(num2)[::-1]
            i,j = 0,0
            while i<len(num1) and j<len(num2):
                num1[i] = str(int(num1[i]) + int(num2[i]))
                i += 1
                j += 1
            # print('num1:',num1)
            # print('num2:',num2)
            # print('i=',i)
            # print('j=',j)
            while j<len(num2):
                num1.append(num2[j])
                j += 1
            carry = 0
            for i in range(len(num1)-1):
                num1[i] = str(int(num1[i]) + carry)
                if int(num1[i])>9:
                    num1[i] = str(int(num1[i])-10)
                    carry = 1
                else:
                    carry = 0
            # print('carry:',carry)
            # print(num1[::-1])
            num1[-1] = str(int(num1[-1]) + carry)
            # print(num1[::-1])
            if int(num1[-1])>9:
                num1[-1] = str(int(num1[-1]) - 10)
                num1.append('1')
            return ''.join(num1[::-1])
    
  • 相关阅读:
    DS博客作业02--栈和队列
    DS博客作业02--线性表
    c博客06-结构
    c博客作业05--指针
    C博客作业04--数组
    博客作业03-函数
    循环结构
    c博客作业01--分支、顺序结构
    我的第一篇博客
    Macos安装JDK1.8
  • 原文地址:https://www.cnblogs.com/bernieloveslife/p/9765651.html
Copyright © 2011-2022 走看看