力扣_day2

发布时间:2024年01月03日

两数相加

用python3更方便,有内置的ListNode。

# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next

class Solution(object):
    def cycles(self,head):
        now = head
        index = 0
        while(now):
            index += 1
            now = now.next
        return index

    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        len1 = self.cycles(l1)
        len2 = self.cycles(l2)
        
        if len1 > len2:
            long_list = l1
            long_len = len1
            short_list = l2
            short_len = len2
        else:
            long_list = l2
            long_len = len2
            short_list = l1
            short_len = len1

        i = 0
        a = short_list
        b = long_list
        flag = 0
        while(i<long_len):
            if i < short_len:
                sum = a.val + b.val + flag
                if sum < 10:
                    b.val = sum
                    flag = 0
                else:
                    b.val = sum % 10
                    flag = 1
                if a.next:
                    a = a.next
                if b.next:
                    b = b.next

            else:
                sum = b.val + flag
                if sum < 10:
                    b.val = sum
                    flag = 0
                else:
                    b.val = sum % 10
                    flag = 1
                if b.next:
                    b = b.next
            
            i += 1
        
        if flag != 0:
            end = ListNode(flag)
            b.next = end

        return long_list

文章来源:https://blog.csdn.net/weixin_43409127/article/details/135373095
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。