美文网首页
2020-02-24 Day2 Leetcode: 2. Add

2020-02-24 Day2 Leetcode: 2. Add

作者: YueTan | 来源:发表于2020-02-24 08:46 被阅读0次

You are given two non-empty linked lists representing two non-negative integers. 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.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Not fullt correct yet

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

class Solution:
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:        
        a_digit=0
        first_digit=True
        result= ListNode(0)
              
        while l1!=None and l2!=None:
            sum=l1.val+l2.val+a_digit 
            
            if first_digit==True:
                result.val=sum%10
                first_digit=False
            else:
                result.next=ListNode(0)
                result.next.val=sum%10
         
            result.val=sum%10
            a_digit=sum//10
            
            l1=l1.next
            l2=l2.next 
        
        return result
            
        

The correct one,
it's important to know the linked list property

class Solution:
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:        
        a_digit=0
        head=result= ListNode(0)
              
        while l1!=None or l2!=None or a_digit>0:
            if l1:
                a_digit+=l1.val
                l1=l1.next
            if l2:
                a_digit+=l2.val
                l2=l2.next
            
            this_val=a_digit%10
            a_digit=a_digit//10        
            
            
            result.next=ListNode(this_val)
            result=result.next        
        
        return head.next

相关文章

网友评论

      本文标题:2020-02-24 Day2 Leetcode: 2. Add

      本文链接:https://www.haomeiwen.com/subject/ttzpqhtx.html