[數據結構][Python][經典題目]大數求和

題目

LeetCode上的算法第415題題目描述:
給定兩個字符串形式的非負整數 num1 和num2 ,計算它們的和。
注意:
num1 和num2 的長度都小於 5100.
num1 和num2 都只包含數字 0-9.
num1 和num2 都不包含任何前導零。
你不能使用任何內建 BigInteger 庫, 也不能直接將輸入的字符串轉換爲整數形式。
LeetCode地址:https://leetcode-cn.com/problems/add-strings/description/

思路

類似加法運算,考慮進位。新建一個數組,數組長度與較長的那個數組一致,數組後一部分保存較短數組的值,其餘部分全爲0,之後利用這個新建的數組
與原較長的數組進行加和運算。從數組尾部加起,如果求和數值大於10,則只保留個位數,並把數組的前一位加1.如果進位後超出數組長度範圍,則用插入操作。
反轉list,各個位數相加,進位

代碼實現

class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: List
        :type l2: List
        :rtype: List
        """
        l1 = list(reversed(l1))
        l2 = list(reversed(l2))
        l1, l2 = self.judgeLen(l1, l2)
        print(l1, l2)
        add_nums = []
        for i in range(len(l1)):
            add_num, flag = self.judgeCarry(l1[i], l2[i])
            if flag == 0:
                add_nums.append(add_num)
            else:
                add_nums.append(add_num)
                try:
                    l1[i + 1] = l1[i + 1] + 1
                except:
                    continue
        if add_nums[-1] == 0:
            add_nums.append(1)
        print(list(reversed(add_nums)))
        res = list(reversed(add_nums))
        return res

    def judgeCarry(self, a, b):
        if a + b > 9:
            return [(a + b) % 10, 1]
        else:
            return [a + b, 0]

    def judgeLen(self, l1, l2):
        lenl1 = len(l1)
        lenl2 = len(l2)
        add_len = []
        for i in range(abs(lenl2 - lenl1)):
            add_len.append(0)
        if lenl1 >= lenl2:
            for i in range(abs(lenl2 - lenl1)):
                l2.append(0)
            # print([l1,add_len])
            return [l1, l2]
        else:
            for i in range(abs(lenl2 - lenl1)):
                l1.append(0)
            add_len.append(l1)
            # print([l2,add_len])
            return [l2, l1]


if __name__ == '__main__':
    S = Solution()
    S.addTwoNumbers([2, 4, 3, 5, 6, 4, 7, 4], [5, 6, 4, 4, 5, 6, 7])

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章