1. 程式人生 > >19.1.11 LeetCode 2 Add Two Numbers

19.1.11 LeetCode 2 Add Two Numbers

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.

Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
 1 class Solution {
 2 public:
 3     ListNode * addTwoNumbers(ListNode* l1, ListNode* l2) {
 4         int num1, num2;
 5         ListNode*ans,*oldans=NULL,*head;
 6
int inc = 0; 7 while (l1!= NULL && l2!= NULL) { 8 num1 = l1->val, num2 = l2->val; 9 int plus = num1 + num2+inc; 10 inc = plus / 10; 11 ans = new ListNode(plus % 10); 12 if (oldans) 13 oldans->next = ans;
14 else 15 head = ans; 16 oldans = ans; 17 ans = ans->next; 18 l1 = l1->next, l2 = l2->next; 19 } 20 while (l1 != NULL) { 21 num1 = l1->val; 22 int plus = num1 + inc; 23 inc = plus / 10; 24 ans = new ListNode(plus % 10); 25 if (oldans) 26 oldans->next = ans; 27 else 28 head = ans; 29 oldans = ans; 30 ans = ans->next; 31 l1 = l1->next; 32 } 33 while (l2!= NULL) { 34 num1 = l2->val; 35 int plus = num1 + inc; 36 inc = plus / 10; 37 ans = new ListNode(plus % 10); 38 if (oldans) 39 oldans->next = ans; 40 else 41 head = ans; 42 oldans = ans; 43 ans = ans->next; 44 l2 = l2->next; 45 } 46 if (inc > 0) { 47 ans = new ListNode(inc); 48 if (oldans) 49 oldans->next = ans; 50 else 51 head = ans; 52 } 53 return head; 54 } 55 };
View Code

普通地做了下模擬,是不是有點太麻煩了呢?