問題
給定兩個非空鏈表來表示兩個非負整數。位數按照逆序方式存儲,它們的每個節點只存儲單個數字。將兩數相加返回一個新的鏈表。
你可以假設除了數字 0 之外,這兩個數字都不會以零開頭。
示例:
輸入:(2 -> 4 -> 3) + (5 -> 6 -> 4) 輸出:7 -> 0 -> 8 原因:342 + 465 = 807
代碼實現
#include <vector>
#include <map>
#include <iostream>
#include <math.h>
/**
*
給定兩個非空鏈表來表示兩個非負整數。位數按照逆序方式存儲,它們的每個節點只存儲單個數字。將兩數相加返回一個新的鏈表。
你可以假設除了數字 0 之外,這兩個數字都不會以零開頭。
示例:
輸入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
輸出:7 -> 0 -> 8
原因:342 + 465 = 807
*/
using namespace std;
struct ListNode{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL){}
};
template<class T>
int length(T& arr) {
return sizeof(arr)/ sizeof(arr[0]);
}
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
uint64_t carry = 0, sum = 0;
ListNode prehead(0), *p = &prehead;
while (l1 || l2) {
sum = (l1 ? l1->val : 0) + (l2 ? l2->val : 0) + carry;
sum = carry / 10;
p->next = new ListNode(sum % 10);
l1 = l1 ? l1->next : l1;
l2 = l2 ? l2->next : l2;
p = p->next;
}
return prehead.next;
}
};
int main(int argc, char** argv){
int a[] = {2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,9};
ListNode* tmp = new ListNode(0);
ListNode* ptr1 = tmp;
for (int i = 0; i < length(a); i++) {
ptr1->next = new ListNode(a[i]);
ptr1 = ptr1->next;
}
ptr1 = tmp->next;
delete tmp;
tmp = new ListNode(0);
int b[] = {5,6,4,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,9,9,9,9};
ListNode* ptr2 = tmp;
for (int j = 0; j < length(b); j ++) {
ptr2->next = new ListNode(b[j]);
ptr2 = ptr2->next;
}
ptr2 = tmp->next;
delete tmp;
Solution* solution = new Solution();
solution->addTwoNumbers(ptr1, ptr2);
delete solution;
return 0;
}
推薦

喜歡編程
浙公網安備 33010602011771號