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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
把较短的字符串的数字加到较长的字符串上,唯一注意的是进位问题
c++代码
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 ListNode *p = l1; 13 ListNode *q = l2; 14 15 int len1 = 0; 16 int len2 = 0; 17 18 while(p != nullptr) 19 { 20 ++ len1; 21 p = p -> next; 22 } 23 24 while(q != nullptr) 25 { 26 ++ len2; 27 q = q -> next; 28 } 29 30 ListNode *res = nullptr; 31 32 if(len1 >= len2) 33 { 34 res = l1; 35 p = l1; 36 q = l2; 37 } 38 else 39 { 40 res = l2; 41 p = l2; 42 q = l1; 43 } 44 45 while(q != nullptr) 46 { 47 p -> val += q -> val; 48 p = p -> next; 49 q = q -> next; 50 } 51 52 ListNode *r = res; 53 54 while(r -> next != nullptr) 55 { 56 if(r -> val >= 10) 57 { 58 int t = r -> val / 10; 59 r -> val = r -> val % 10; 60 r -> next -> val += t; 61 } 62 63 r = r -> next; 64 } 65 66 if(r -> val >= 10) 67 { 68 int t = r -> val / 10; 69 r -> val %= 10; 70 ListNode *tmp = new ListNode(t); 71 r -> next = tmp; 72 } 73 return res; 74 } 75 };