题目描述:
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.
样例:
1 2 3
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807.
题意:
给你两个表示非负数字的链表。数字以相反的顺序存储,其节点包含单个数字。将这两个数字相加并将其作为另外一个链表返回。
题解:
这道题其实就是一个暴力,时间的长短,主要就是看怎么一个写法,蚊子第一次的解法是这样的:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
class {public : ListNode* addTwoNumbers (ListNode* l1, ListNode* l2) { ListNode *ans = new ListNode(0 ); ListNode *head = ans; int res = 0 ; while (l1 != NULL && l2 != NULL ){ int num = l1->val + l2->val + res; res = num / 10 ; num %= 10 ; ans->next = new ListNode(num); ans = ans->next; l1 = l1->next; l2 = l2->next; } while (l1 != NULL ){ int num = l1->val + res; res = num / 10 ; num %= 10 ; ans->next = new ListNode(num); ans = ans->next; l1 = l1->next; } while (l2 != NULL ){ int num = l2->val + res; res = num / 10 ; num %= 10 ; ans->next = new ListNode(num); ans = ans->next; l2 = l2->next; } if (res > 0 ){ ans->next = new ListNode(res); } return head->next; } };
Runtime:40ms Memory:19.2MB faster than 96.34%
康了一下网友的题解,大致都跟蚊子的一样,这里就不拖出来康了。
近期评论