ADD Numbers
- Total accepted:160702
- Total submissions:664770
- Difficulty:medium
You are given, linked lists representing, and non-negative numbers. The digits is stored in reverse order and all of their nodes contain a single digit. ADD the numbers and return it as a linked list.
Input: (2, 4, 3) + (5, 6, 4)
Output:7, 0, 8
The idea of the subject is very simple, the structure of two lists are from low to high order, after-tax requirements to return the linked list is also such a structure. So we only need to loop two linked lists sequentially, add the number of corresponding bits, and determine if there is a carry, and the rounding will be added to the next one.
1 /**2 * Definition for singly-linked list.3 * public class ListNode {4 * int val;5 * ListNode Next;6 * ListNode (int x) {val = x;}7 * }8 */9 Public classNum2 {Ten PublicListNode addtwonumbers (listnode L1, ListNode L2) { One if(L1 = =NULL){ A returnL2; - } - if(L2 = =NULL){ the returnL1; - } - intNextbit = (l1.val + l2.val)/10 ; - intCurbit = (l1.val + l2.val)%10 ; +ListNode head =NewListNode (curbit); -ListNode temp =head; +L1 =L1.next; AL2 =L2.next; at //when the corresponding bits of L1 and L2 are present, the calculation - while(L1! =NULL&& L2! =NULL){ -Curbit = (l1.val + l2.val + nextbit)% 10 ; -Nextbit = (l1.val + l2.val + nextbit)/10 ; -ListNode node =NewListNode (curbit); -Temp.next =node; intemp =Temp.next; -L1 =L1.next; toL2 =L2.next; + } - //judge whether the L1 is over, no end to continue the while(L1! =NULL){ *Curbit = (l1.val + nextbit)% 10 ; $Nextbit = (l1.val + nextbit)/10 ;Panax NotoginsengListNode node =NewListNode (curbit); -Temp.next =node; thetemp =Temp.next; +L1 =L1.next; A } the //judge whether the L2 is over, no end to continue + while(L2! =NULL){ -Curbit = (l2.val + nextbit)% 10 ; $Nextbit = (l2.val + nextbit)/10 ; $ListNode node =NewListNode (curbit); -Temp.next =node; -temp =Temp.next; theL2 =L2.next; - }Wuyi //determines whether the last carry bit is 0, not 0 to save the next the if(Nextbit! = 0){ -ListNode node =NewListNode (nextbit); WuTemp.next =node; - } About returnHead; $ } -}
No.2 Add Numbers