Leetcode两数相加
本人代码:
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
int x = 1;
int it1=0, it2=0;
int ra = 1;
int acc=0, i=0, y=1;
int num[2000];
ListNode *p1 = l1;
ListNode *p2 = l2;
while(p1)
{
x = p1->val;
x *= ra;
it1 += x;
ra *= 10;
p1 = p1->next;
}
ra = 1;
while(p2)
{
x = p2->val;
x *= ra;
it2 += x;
ra *= 10;
p2 = p2->next;
}
acc = it1 + it2;
while(acc)
{
num[i] = acc%10;
acc /= 10;
i++;
}
ListNode *head = new ListNode;
ListNode *end = new ListNode;
head->val = num[0];
end = head;
while(y < i)
{
ListNode* temp = new ListNode;
temp->val = num[y];
if(end != NULL)
end->next = temp;
end = temp;
if(end->val ==0 && y==i)
cout<<temp->val;
y++;
}
end ->next = nullptr;
return head;
}
};
样例:
实际提交: