版本1:定義了和爲int型或者long型,但實際上提交時會出現溢出錯誤
版本2:直接利用定義相加
反思:
一開始題意沒有理解清楚,就暴力法求和相加解決,進而發現有可能會導致整數溢出,這也提醒我們在使用c++的時候,一定要關注數的表示範圍。
再次理解題意之後,利用題目定義求解,會發現非常簡單。
//版本一
struct ListNode{
int val;
ListNode *next;
ListNode(int x): val(x), next(NULL) {}
};
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode *p = l1;
ListNode *q = l2;
long sum1=0, sum2=0, sum=0;//int
int count1=0, count2=0;
while(p){
sum1 += (p->val) * pow(10, count1);
p = p->next;
count1 += 1;
}
while(q){
sum2 += (q->val) * pow(10, count2);
q = q->next;
count2 += 1;
}
sum = sum1 + sum2;
int max = count1>count2 ? count1:count2;
int N;
if(sum >= pow(10, max))
N = max+1;
else
N = max;
ListNode *head = new ListNode(0);
ListNode *r = head;
int count = 0;
int tempVal;
while(N >count){
tempVal = (sum%(int)pow(10, count+1)) / (int)pow(10, count);
ListNode *tempPtr = new ListNode(tempVal);
r->next = tempPtr;
r = r->next;
count += 1;
}
return head->next;
}
};
//版本二
class Solution{
public:
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2){
ListNode *p = l1;
ListNode *q = l2;
ListNode *head = new ListNode(0);
ListNode *r = head;
int temp = 0;
int flag = 0;
while(p || q || flag){
temp = flag;
if(p)
temp += p->val;
if(q)
temp += q->val;
flag = temp/10;
temp = temp%10;
ListNode *tempPtr = new ListNode(temp);
r->next = tempPtr;
r = r->next;
if(p && p->next)
p = p->next;
else
p = NULL;
if(q && q->next)
q = q->next;
else
q = NULL;
}
return head->next;
}
};