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.
class(object): defaddTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ ifnot l1 ornot l2: return l1 ifnot l2 else l2 head = ListNode(0) p,q = l1,l2 flg = 0 cur = head while p and q: val = (flg+p.val+q.val)%10 new = ListNode(val) cur.next = new flg = (flg+p.val+q.val)/10 p = p.next q= q.next cur = cur.next while p: val = (flg+p.val)%10 new = ListNode(val) cur.next = new flg = (flg+p.val)/10 p = p.next cur = cur.next while q: val = (flg+q.val)%10 new = ListNode(val) cur.next = new flg = (flg+q.val)/10 q = q.next cur = cur.next if flg>0: new = ListNode(flg) cur.next = new return head.next
类似题目:
Multiply Strings Add Binary Sum of Two Integers Add Strings Add Two Numbers II Add to Array-Form of Integer
近期评论