Test instructions: There are two linked lists, which represent two non-negative numbers in reverse order. Example (2, 4, 3) represents 342, which is two digits and is output in reverse order in the same way. As 342+465 = 807, you need to show the result as (7->0->8). Idea: Simulation of the addition of the operation process, from the start of the bit, carry save down, 10 bits of the operation when the digit of the plus, and so on. C + + Code
/** Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x) : Val (x), Next (NULL) {}}; */classSolution { Public: ListNode* AddTwoNumbers (listnode* L1, listnode*L2) {ListNode Prehead (0), *p = &Prehead; intExtra =0; while(L1 | | l2 | |extra) { intsum = (L1? L1->val:0) + (L2? L2->val:0) +Extra; Extra= SUM/Ten; P->next =NewListNode (sum%Ten); P= p->Next; L1= L1? L1->next:l1; L2= L2? L2->Next:l2; } returnPrehead.next; }};Python Code
#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:ListNode"""P= Prehead =listnode (0) Extra=0 whileL1orL2orExtra:extra, Val= Divmod ((L1 andL1.valor0) + (L2 andL2.valor0) + Extra, 10) P.next=ListNode (val) P=P.nextifL1:L1=L1.nextifL2:l2=L2.nextreturnPrehead.next
JS Code
/** Definition for singly-linked list. * Function ListNode (val) {* This.val = val; * This.next = null; *}
*//** * @param {listnode} L1 * @param {listnode} L2 * @return {ListNode}*/varAddTwoNumbers =function(L1, L2) {varPrehead =NewListNode (0) varp =PreheadvarExtra = 0 while(L1!==NULL|| L2!==NULL|| Extra!== 0) { varsum = (L1 && l1.val | | 0) + (L2 && L2.val | | 0) +Extra Extra= (Sum > 9)? 1:0P.next=NewListNode (sum% 10) P=p.next L1= L1 && L1.next | |NULLL2= L2 && L2.next | |NULL } returnPrehead.next};
Leetcode 2. ADD Numbers Problem Solving report