1. 程式人生 > >[leetcode] 2. Add Two Numbers

[leetcode] 2. Add Two Numbers

code eve ini emp any n-n self 申請 tno

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.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8


就是簡單的高精度加法,剛開始理解錯題意WA了好幾次。

要註意的是:

判斷兩個list有沒有都算到頭;

判斷進位是否為0;

考慮有沒有多申請節點,最後一個節點不能為0。


以下是我的代碼:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 
*/ class Solution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { ListNode* re = new ListNode(0); ListNode* result = re; int carry = 0; while (l1 || l2 || carry) { int tmp = (l1?(l1->val):0) + (l2?(l2->val):0) + carry; re->val = tmp % 10
; carry = tmp / 10; if (l1) l1 = l1->next; if (l2) l2 = l2->next; if (l1 || l2 || carry) re->next = new ListNode(0), re = re->next; } return result; } };

[leetcode] 2. Add Two Numbers