Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807.
1 class ListNode { 2 int val; 3 ListNode next; 4 5 ListNode(int x) { //对应结构体初始化为ListNode(int data=0,struct ListNode next=NULL):val(val),next(next){} 6 val = x; 7 next = null; 8 } 9 } 10 11 class Solution5 { 12 ListNode addTwoNumbers(ListNode l1, ListNode l2) { 13 ListNode preHead = new ListNode(0); 14 ListNode p = l1, q = l2, curr = preHead; 15 int carry = 0; 16 while (p != null || q != null) { 17 int x = (p != null) ? p.val : 0; 18 int y = (q != null) ? q.val : 0; 19 int sum = x + y + carry; //进位处理,并在下一个节点处进行处理 20 carry = sum / 10; 21 curr.next = new ListNode(sum % 10); //新构造一个节点 22 curr = curr.next; 23 if (p != null) p = p.next; 24 if (q != null) q = q.next; 25 } 26 if (carry > 0) { //处理多一位 27 curr.next = new ListNode(carry); 28 } 29 return preHead.next; 30 } 31 }
此题基本就是用链表处理大数,所以用int+ListNode的方式来处理大数问题,只是应该找到其适用场景,譬如较多的写操作、内存占用等。
1 #include <bits/stdc++.h> 2 #include <map> 3 #include <vector> 4 using namespace std; 5 6 struct ListNode 7 { 8 int val; 9 struct ListNode *next; 10 ListNode(int data = 0, struct ListNode *next = NULL) : val(val), next(next) {} //初始化链表 11 }; 12 13 class Solution 14 { 15 public: 16 ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) 17 { 18 ListNode preHead(0), *p = &preHead; 19 int carry = 0; 20 while (l1 || l2) 21 { 22 int sum = (l1 ? l1->val : 0) + (l2 ? l2->val : 0) + carry; 23 carry = sum / 10; 24 p->next = new ListNode(sum % 10); 25 p = p->next; 26 l1 = l1 ? l1->next : l1; 27 l2 = l2 ? l2->next : l2; 28 } 29 if (carry > 0) 30 { //处理多一位 31 p->next = new ListNode(carry); 32 } 33 return preHead.next; 34 }