Description
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 1 2 3 4 5 Input: (2 -> 4 -> 3 ) + (5 -> 6 -> 4 ) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807.
Interface 1 2 3 4 5 6 7 8 9 10 11 12 13 14 class Solution {public : ListNode* addTwoNumbers (ListNode* l1, ListNode* l2) { } };
Solution 题目挺简单的,就是通过链表实现大数加法,结果的每一位由三个值决定,两个是两个加数在这个数位上的值,剩下一个是上一位的进位,主要就是需要注意进位的实现,也没什么难度,可能还有需要注意的就是代码的逻辑需要简明清晰,不然很容易写的很冗长。
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 class Solution {public : ListNode* addTwoNumbers (ListNode *l1, ListNode *l2) { int n1 = 0 , n2 = 0 , tmp = 0 , carry = 0 ; ListNode *p1 = l1, *p2 = l2, *temp = NULL , *result = NULL ; while (p1 != NULL || p2 != NULL || carry != 0 ) { n1 = (p1 != NULL ) ? p1->val : 0 ; n2 = (p2 != NULL ) ? p2->val : 0 ; tmp = n1 + n2 + carry; carry = tmp / 10 ; if (result == NULL ) result = new ListNode(tmp % 10 ); else temp->next = new ListNode(tmp % 10 ); p1 = (p1 == NULL ) ? p1 : p1->next; p2 = (p2 == NULL ) ? p2 : p2->next; if (temp == NULL ) temp = result; else temp = temp->next; } return result; } };
Improvement 在 LeetCode 讨论区中发现了更简洁的代码。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 ListNode* addTwoNumbers (ListNode *l1, ListNode *l2) { ListNode preHead(0), *p = &preHead; int extra = 0 ; while (l1 || l2 || extra) { int sum = (l1 ? l1->val : 0 ) + (l2 ? l2->val : 0 ) + extra; extra = sum / 10 ; p->next = new ListNode(sum % 10 ); p = p->next; l1 = l1 ? l1->next : l1; l2 = l2 ? l2->next : l2; } return preHead.next; }
如有疑问请联系作者,联系方式:weijia_sysu@163.com