struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
/*
struct ListNode * head=NULL;
struct ListNode * p;
struct ListNode * tail;
unsigned long long cnt1=0;
unsigned long long cnt2=0;
unsigned long long exp=1;
while(l1){
cnt1+=l1->val*exp;
exp*=10;
l1=l1->next;
}
exp=1;
while(l2){
cnt2+=l2->val*exp;
exp*=10;
l2=l2->next;
}
unsigned long long cnt = cnt1+cnt2;
printf("%d ",cnt);
if(cnt==0){
p=(struct ListNode * )malloc(sizeof(struct ListNode));
head=p;
p->next=NULL;
p->val=0;
return head;
}
while(cnt>0){
int temp=cnt%10;
p=(struct ListNode * )malloc(sizeof(struct ListNode));
if(head==NULL){
head=p;
p->next=NULL;
p->val=temp;
tail= p;
}else{
tail->next=p;
p->next=NULL;
p->val=temp;
tail= p;
}
cnt =cnt/10;
}
*/
//做到这里发现一个问题:溢出的问题
//换一个思路(´;ω;`)
//又出现了一个问题:进位的问题(´;ω;`)
//不像数组那么好处理
//为什么不直接转化为数组呢?
bool define(int a[101],int b[101],int i){
for(int j = i;j<101;j++){
if(a[j]!=0||b[j]!=0){
return false;
}
}
return true;
}
int a[101]={0};
int b[101]={0};
int c[101]={0};
/*
for(int i = 0;i<101;i++){
a[i]=b[i]=-1;
}
*/
int cnt1=0;
int cnt2=0;
while(l1){
a[cnt1]=l1->val;
l1=l1->next;
++cnt1;
}
while(l2){
b[cnt2]=l2->val;
l2=l2->next;
++cnt2;
}
int end;
for(int i = 0;i<101;i++){
if(a[i]+b[i]>=10){
c[i]+=(a[i]+b[i])%10;
a[i+1]+=1;
}else{
c[i]+=a[i]+b[i];
}
if(define(a,b,i)){
end=i;
break;
}
}
struct ListNode * head=NULL;
struct ListNode * p;
struct ListNode * tail;
if(end==0){
p=(struct ListNode * )malloc(sizeof(struct ListNode));
head=p;
p->next=NULL;
p->val=0;
return head;
}
for(int i = 0;i<end;i++){
if(head==NULL){
p=(struct ListNode * )malloc(sizeof(struct ListNode));
head=p;
p->next=NULL;
p->val=c[i];
tail=p;
}else{
p=(struct ListNode * )malloc(sizeof(struct ListNode));
tail->next=p;
p->val=c[i];
p->next=NULL;
tail=p;
}
}
return head;
}
bool define(int a[101],int b[101],int i){
for(int j = i;j<101;j++){
if(a[j]!=0||b[j]!=0){
return false;
}
}
return true;
}
LeetCode_2两数相加
于 2023-12-07 20:27:58 首次发布