leetcode -- Add Two Numbers
You are given two linked lists representing two non-negative numbers. 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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
注意有进位
version 1
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { 7 * val = x; 8 * next = null; 9 * } 10 * } 11 */ 12 public class Solution { 13 public ListNode addTwoNumbers(ListNode l1, ListNode l2) { 14 // Start typing your Java solution below 15 // DO NOT write main() function 16 ListNode result = new ListNode(l1.val + l2.val); 17 ListNode pointer = result; 18 19 while(l1.next != null && l2.next != null){ 20 l1 = l1.next; 21 l2 = l2.next; 22 ListNode node = new ListNode(l1.val + l2.val); 23 pointer.next = node; 24 pointer = node; 25 } 26 27 while(l1.next != null){ 28 l1 = l1.next; 29 ListNode node = new ListNode(l1.val); 30 pointer.next = node; 31 pointer = node; 32 } 33 34 while(l2.next != null){ 35 l2 = l2.next; 36 ListNode node = new ListNode(l2.val); 37 pointer.next = node; 38 pointer = node; 39 } 40 41 pointer = result; 42 while(pointer.next != null){ 43 if(pointer.val >= 10){ 44 int remainders = pointer.val % 10; 45 int quotients = pointer.val / 10; 46 pointer.val = remainders; 47 pointer.next.val += quotients; 48 } 49 pointer = pointer.next; 50 } 51 52 while(pointer.val >= 10){ 53 ListNode node = new ListNode(pointer.val / 10); 54 pointer.next = node; 55 pointer.val = pointer.val % 10; 56 pointer = pointer.next; 57 } 58 59 return result; 60 } 61 }
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) { 12 if (l1 == NULL){ 13 return l2; 14 } 15 if (l2 == NULL){ 16 return l1; 17 } 18 19 ListNode *head = new ListNode(-1); 20 ListNode *p = head; 21 int carry = 0; 22 while (l1 != NULL && l2 != NULL){ 23 int sum = l1->val + l2->val + carry; 24 if (sum >= 10){ 25 carry = sum / 10; 26 sum = sum % 10; 27 } 28 else { 29 carry = 0; 30 } 31 ListNode* tmp = new ListNode (sum); 32 p->next = tmp; 33 p = p->next; 34 35 l1 = l1->next; 36 l2 = l2->next; 37 } 38 39 while (l1 != NULL) { 40 int sum = l1->val + carry; 41 if (sum >= 10) { 42 carry = sum / 10; 43 sum = sum % 10; 44 } else { 45 carry = 0; 46 } 47 ListNode* tmp = new ListNode(sum); 48 p->next = tmp; 49 p = p->next; 50 l1 = l1->next; 51 } 52 53 while (l2 != NULL) { 54 int sum = l2->val + carry; 55 if (sum >= 10) { 56 carry = sum / 10; 57 sum = sum % 10; 58 } 59 else { 60 carry = 0; 61 } 62 ListNode* tmp = new ListNode(sum); 63 p->next = tmp; 64 p = p->next; 65 l2 = l2->next; 66 } 67 68 if (carry != 0) { 69 ListNode *tmp = new ListNode(carry); 70 p->next = tmp; 71 } 72 73 return head->next; 74 } 75 };