欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

LeetCode2 两数相加

程序员文章站 2022-04-04 09:03:20
...

题目描述

该题为中等难度,链表、进位
LeetCode2 两数相加

解题

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        l3 = ListNode(0)
        r = l3
        p = l1
        q = l2
        carry = 0
        temp = 0
        while (p or q):
            if not p:
                val1 = 0
            else:
                 val1 = p.val
            if q:
                val2 = q.val
            else:
                val2 = 0
            temp = val1+val2+carry
            carry = temp/10
            val = temp%10
            r.next = ListNode(val)
            if p:
                p=p.next
            if q:
                q = q.next
            r = r.next
        if carry!=0:#最后的进位
            r.next = ListNode(1)
        return l3.next
相关标签: LeetCode