[LeeCode]Add Two Numbers

来源:互联网 发布:淘宝vr眼镜宣传视频 编辑:程序博客网 时间:2024/05/21 12:08

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.

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

Subscribe to see which companies asked this question.

class Solution(object):    def addTwoNumbers(self, l1, l2):        Head = ListNode(0)        ans = Head        rem  = 0        while True:            if l1 != None:                rem += l1.val                l1 = l1.next            if l2 != None:                rem += l2.val                l2 = l2.next            ans.val = rem % 10            rem /= 10            if l1 != None or l2 != None or rem != 0:                ans.next = ListNode(0)                ans = ans.next            else: break        return Head

原创粉丝点击