首页 > 代码库 > LeetCode-Add two Numbers
LeetCode-Add two Numbers
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* ans = l1;
while(1){
l1->val +=l2->val;
if(l1->next == NULL){
if(l2->next == NULL){
if(l1->val>9){
l1->next = new ListNode(1);
l1->val %=10;
}
return ans;
}
l1->next = new ListNode(0);
}
if(l2->next==NULL){
l2->next = new ListNode(0);
}
l1->next->val+=l1->val/10;
l1->val%=10;
l1=l1->next;
l2=l2->next;
}
}
};
1559 / 1559 test cases passed.
Status: Accepted
Runtime: 35 ms
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode *ansd =new ListNode(0);
ListNode *ans = ansd;
int as = 0;
while(l1||l2||as!=0){
if(l1){
as+=l1->val;
l1 = l1->next;
}
if(l2){
as+=l2->val;
l2 = l2->next;
}
if(as>9){
ans->next = new ListNode(as-10);
as = 1;
}else{
ans->next = new ListNode(as);
as = 0;
}
ans = ans->next;
}
return ansd->next;
}
};
1562 / 1562 test cases passed.
Status: Accepted
Runtime: 32 ms
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode *ans = l1;
while(l1->next&&l2->next){
l1->val+=l2->val;
if(l1->val>9){
l1->val-=10;
l1->next->val+=1;
}
l1 = l1->next;
l2 = l2->next;
}
while(l1->next == NULL && l2 -> next){
l1 ->next = new ListNode(0);
l1 ->val += l2 ->val;
if(l1 -> val>9){
l1 ->val -= 10;
l1 ->next ->val +=1;
}
l1 = l1 ->next;
l2 = l2 ->next;
}
{
l1->val+=l2->val;
while(l1->val>9){
l1->val-=10;
if(l1->next == NULL){
l1->next = new ListNode(0);
}
l1->next->val+=1;
l1=l1->next;
}
}
return ans;
}
};
1562 / 1562 test cases passed.
Status: Accepted
Runtime: 32 ms
LeetCode-Add two Numbers
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。