445. ADD Numbers ii--while S1 or S2 or carry the topic and more simple test cases

Source: Internet
Author: User
Tags add numbers

You are given, linked lists representing, and non-negative numbers. The most significant digit comes first and all of their nodes contain a single digit. ADD the numbers and return it as a linked list.

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

Follow up:
What if cannot modify the input lists? In other words, reversing the lists are not allowed.

Example:

Input: (7, 2, 4, 3) + (5, 6, 4)Output: 7, 8, 0, 7
#Definition for singly-linked list.#class ListNode (object):#def __init__ (self, x):#self.val = x#Self.next = Noneclasssolution (object):defaddtwonumbers (self, L1, L2):""": Type L1:ListNode:type l2:ListNode:rtype:ListNodeInput: (7, 2, 4, 3) + (5-& Gt               6, 4) 77->2->4->3 5->6->4=-------------7->7->0->7->1 output:7, 8, 0 """S1,s2=[],[] p1,p2=L1,l2 whilep1:s1.append (p1.val) P1=P1.next whilep2:s2.append (p2.val) P2=P2.next Carry=0 Fake_head=ListNode (None) whileS1orS2orCarry:v1= S1.pop ()ifS1Else0 v2= S2.pop ()ifS2Else0 Val= v1 + v2 +CarryifVal >= 10: Val-= 10Carry= 1Else: Carry=0 Head=ListNode (val) head.next=Fake_head.next Fake_head.next=HeadreturnFake_head.next

445. Add, Numbers ii--while S1 or S2 or carry the topic again. Test Cases

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.