版本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;
}
};