错误示范:将两链表转成两数,再相加,还要注意处理前导零。。
最后1565 / 1568 个通过测试用例,卡死在[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]
错误原因:runtime error: signed integer overflow: 10 * 1000000000000000000 cannot be represented in type ‘long long’ (solution.cpp)
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
typedef long long ll;
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ll tmp1=0,tmp2=0,num1,num2,ans=0,cnt1=0,cnt2=0;
bool flag1=true,flag2=true;
for(ListNode* i=l1;i!=nullptr;i=i->next)
{
if(flag1&&i->val==0)
cnt1++;
else
{
flag1=false;
tmp1=tmp1<<1+i->val;
}
}
for(ListNode* j=l2;j!=nullptr;j=j->next)
{
if(flag2&&j->val==0)
cnt2++;
else
{
flag2=false;
tmp2=tmp2<<1+j->val;
}
}
num1=tmp1%10;
num2=tmp2%10;
for(ll i=tmp1/10;i>0;i=i/10)
num1=10*num1+i%10;
for(ll i=tmp2/10;i>0;i=i/10)
num2=10*num2+i%10;
if(num1!=0)
num1*=pow(10,cnt1);
if(num2!=0)
num2*=pow(10,cnt2);
ans=num1+num2;
ListNode* x=new ListNode(ans%10,nullptr);
ListNode* p=x;
for(ll i=ans/10;i>0;i=i/10)
{
p->next=new ListNode(i%10,nullptr);
p=p->next;
}
return x;
}
};
正确示范:直接从两链表头遍历,相加,正好符合从低位加到高位,维护一个进位变量
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode *dHead = new ListNode(0,nullptr), *pre;
pre=dHead;
int t = 0;
while (l1 != nullptr || l2 != nullptr || t != 0) {
if (l1 != nullptr) {
t += l1->val;
l1 = l1->next;
}
if (l2 != nullptr) {
t += l2->val;
l2 = l2->next;
}
pre->next = new ListNode(t % 10);
pre = pre->next;
t /= 10;
}
return dHead->next;
}
};