2. 两数相加
程序员文章站
2022-04-17 15:51:30
...
符号溢出
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
long long number(ListNode *l){
long long t=1;
long long sum=0;
while(l!=NULL){
sum=sum+t*l->val;
l=l->next;
t*=10;
}
return sum;
}
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
// ListNode l;
cout<<"l1:"<<number(l1);
cout<<endl;
cout<<"l2:"<<number(l2);
long long lNum=number(l1)+number(l2);
ListNode *head=new ListNode (0);
ListNode *m;
m=head;
if(lNum==0) return head ;
while(lNum){
m->next=new ListNode(lNum%10);
lNum/=10;
m=m->next;
}
return head->next;
}
};
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
ret=cur=ListNode(0)
add=0
while(l1!=None or l2!=None or add):
val=(l1.val if l1 else 0)+ (l2.val if l2 else 0)+add
add=(val)//10
cur.next=ListNode(val%10)
cur=cur.next
l1=l1.next if l1 else None
l2=l2.next if l2 else None
return ret.next
c++ 版本
/**
* 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 *head=new ListNode(0);
ListNode *p;
p=head;
int add=0;
while(l1 ||l2 ||add){
int val= (l1==NULL?0:l1->val)+(l2==NULL?0:l2->val)+add;
add =val/10;
p->next=new ListNode(val%10);
p=p->next;
l1=(l1==NULL?NULL:l1->next);
l2=(l2==NULL? NULL :l2->next);
}
return head->next;
}
};
上一篇: WordPress自定义编写面板指南
下一篇: 2. 两数相加