最容易想到的就是把链表里面的数取出来按倒序组成数,然后两个链表中的数字相加得到一个新数
再把这个数拆开放到链表里面。 注意要用long 型,用int 型会溢出。这个方法如果输入的数字再多一点就没法求了,毕竟long型也是有限的。运行了40ms
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { ListNode *result,*tempnode,*prenode; ListNode *l1_current = l1; ListNode *l2_current = l2; int p = 0; long sum1 = 0; long sum2 = 0; long sum3 = 0; vector<int> ivec; while (l1_current != NULL ) { sum1 += l1_current->val*pow(10, p); ++p; l1_current = l1_current->next; } p = 0; while (l2_current != NULL) { sum2 += l2_current->val*pow(10, p); ++p; l2_current = l2_current->next; } sum3 = sum1 + sum2; long s = sum3; result = new ListNode(s % 10); prenode = result; s /= 10; while(s) { tempnode = new ListNode( s % 10); prenode->next = tempnode; prenode = tempnode; s /= 10; } return result; }
还有一种方法就是一位一位的加,每次加的时候保存一个进位数字,我用的是容器保存,代码也没有简化,最容易理解。这个运行了48ms
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { ListNode *result = NULL,*tempnode,*prenode; ListNode *l1_current = l1; ListNode *l2_current = l2; vector<int> ivec; vector<int> ivec1; vector<int> ivec2; while (l1_current != NULL) { ivec1.push_back(l1_current->val); l1_current = l1_current->next; } while (l2_current != NULL) { ivec2.push_back(l2_current->val); l2_current = l2_current->next; } int cnt = 0; int i = 0; for (; i != ivec1.size() && i != ivec2.size(); ++i) { ivec.push_back((ivec1[i] + ivec2[i] + cnt) % 10); cnt = (ivec1[i] + ivec2[i] + cnt) / 10; } if (ivec1.size() <= ivec2.size()) { for (i; i != ivec2.size(); ++i) { ivec.push_back((ivec2[i] + cnt) % 10); cnt = (ivec2[i] + cnt) / 10; } } else { for (i; i != ivec1.size(); ++i) { ivec.push_back((ivec1[i] + cnt) % 10); cnt = (ivec1[i] + cnt) / 10; } } if (cnt == 1) ivec.push_back(1); if (ivec.size() > 0) { tempnode = new ListNode(ivec[0]); result = tempnode; prenode = tempnode; } else { return NULL; } for (int i = 1; i != ivec.size(); ++i) { tempnode = new ListNode(ivec[i]); prenode->next = tempnode; prenode = tempnode; } return result; }
如果简化后应该是这样的:
class Solution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { if (listLength(l1) < listLength(l2)) return addTwoNumbers(l2, l1); ListNode *r1 = l1, *r2 = l2; int c = 0; bool isEnd = false; while (r2) { int val = r1 -> val + r2 -> val + c; r1 -> val = val % 10; c = val / 10; if (r1 -> next) r1 = r1 -> next; else isEnd = true; r2 = r2 -> next; } while (c) { int val = isEnd ? c : r1 -> val + c; if (isEnd) r1 -> next = new ListNode(val % 10); else r1 -> val = val % 10; c = val / 10; if (r1 -> next) r1 = r1 -> next; else isEnd = true; } return l1; } private: int listLength(ListNode* head) { return head ? 1 + listLength(head -> next) : 0; } };
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-22 03:28:31