LeetCode #2: Add Two Numbers

来源:互联网 发布:excel数据自动更新 编辑:程序博客网 时间:2024/05/21 19:57

Problem Statement

(Problem Link) You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)Output: 7 -> 0 -> 8

Approach 1

# Definition for singly-linked list.# class ListNode(object):#     def __init__(self, x):#         self.val = x#         self.next = Noneclass Solution(object):    def addTwoNumbers(self, l1, l2):        """        :type l1: ListNode        :type l2: ListNode        :rtype: ListNode        """        head_val = l1.val + l2.val        carry = 0        if head_val >= 10:            head_val -= 10            carry = 1        head = ListNode(head_val)        l1, l2 = l1.next, l2.next        p = head        while l1 or l2 or carry:            temp = carry            if l1:                temp += l1.val                l1 = l1.next            if l2:                temp += l2.val                l2 = l2.next            if temp >= 10:                temp -= 10                carry = 1            else:                carry = 0            p.next = ListNode(temp)            p = p.next        return head
0 0
原创粉丝点击