ListNode* addTwoNumbers(ListNode* l1, ListNode* l2){ int carry = 0;//进位 ListNode* result = new ListNode(0); result->next = new ListNode(0); ListNode* cur = result->next; while (l1 != NULL || l2 != NULL || carry) { if (l1 == NULL)l1 = new ListNode(0); if (l2 == NULL)l2 = new ListNode(0); cur->val = (l1->val + l2->val+ carry) % 10; carry = (l1->val + l2->val + carry) / 10; l1 = l1->next; l2 = l2->next; if (l1 != NULL || l2 != NULL || carry) { cur->next = new ListNode(0); cur = cur->next; } } return result->next; }
intmain() { ListNode* a1 = new ListNode(2); a1->next = new ListNode(4); a1->next->next = new ListNode(3); ListNode* a2 = new ListNode(5); a2->next = new ListNode(6); a2->next->next = new ListNode(4); ListNode* b = addTwoNumbers(a1,a2);
return0; }
代码如下(解法二)
通过
1 2
执行用时:24 ms, 在所有 C++ 提交中击败了97.43 %的用户 内存消耗:8.6 MB, 在所有 C++ 提交中击败了100.00 %的用户
ListNode* addTwoNumbers2(ListNode* l1, ListNode* l2){ int c = 0, temp = 0; ListNode* t1 = l1, * t2 = l2; while (t1->next != NULL && t2->next != NULL) { temp = (t1->val + t2->val + c) / 10; t1->val = (t1->val + t2->val + c) % 10; c = temp; t1 = t1->next; t2 = t2->next; } if (t1->next == NULL && t2->next == NULL) { temp = t1->val + t2->val + c; if (temp > 9) t1->next = new ListNode(temp / 10); t1->val = temp % 10; } else { if (t1->next == NULL) t1->next = t2->next; temp = (t1->val + t2->val + c) / 10; t1->val = (t1->val + t2->val + c) % 10; c = temp; t1 = t1->next; while (c != 0 && t1->next != NULL) { temp = t1->val + c; t1->val = temp % 10; c = temp / 10; t1 = t1->next; } if (c != 0) { if (t1->val + c > 9) t1->next = new ListNode(1); t1->val = (t1->val + c) % 10; } } return l1; }
intmain() { ListNode* a1 = new ListNode(2); a1->next = new ListNode(4); a1->next->next = new ListNode(3); ListNode* a2 = new ListNode(5); a2->next = new ListNode(6); a2->next->next = new ListNode(4); ListNode* b = addTwoNumbers(a1,a2);