Day2 LeetCode

2. 两数相加

写完感觉其实也不难,就是写题中总有一些没有考虑的地方。以及LeetCode对指针的要求很严格,不能存在空指针,必须先指向NULL,不然就会出现报错。虽然LeetCode不充值会员不能调试,但是可以通过把想要输出的数据存入最终输出的数据输出来调试数据。

struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){
    int temp1[100],temp2[100],result[100],i,i1,i2,j1,j2,temp,k;
    i1=i2=0;
    while(l1!=NULL||l2!=NULL){
        if(l1!=NULL){
            temp1[i1++]=l1->val;
            l1=l1->next;
        }
        if(l2!=NULL){
            temp2[i2++]=l2->val;
            l2=l2->next;
        }
    }
    j1=j2=0;
    temp=k=0;
    while(j1<i1&&j2<i2){
        if(temp1[j1]+temp2[j2]+temp<10){
            result[k++]=temp1[j1++]+temp2[j2++]+temp;
            temp=0;
        }
        else{
            result[k++]=(temp1[j1]+temp2[j2]+temp)%10;
            temp=(temp1[j1++]+temp2[j2++]+temp)/10;
        }
    }
    //l2长度大于l1
    while(j2<i2){
        if(j2>=i2)
            break;
        if(temp2[j2]+temp<10){
            result[k++]=temp2[j2++]+temp;   
            temp=0;
        }
        else{
            result[k++]=(temp2[j2]+temp)%10;
            temp=(temp2[j2++]+temp)/10;
        }
    }
    //l1长度大于l2
    while(j1<i1){
        if(j1>=i1)
            break;
        if(temp1[j1]+temp<10){
            result[k++]=temp1[j1++]+temp;
            temp=0;
        }
        else{
            result[k++]=(temp1[j1]+temp)%10;
            temp=(temp1[j1++]+temp)/10;
        }
    }
    if(temp!=0)
        result[k++]=temp;
    struct ListNode* l3;
    l3=(struct ListNode*)malloc(sizeof(struct ListNode));
    struct ListNode *r,*s;
    r=l3;
    for(i=0;i<k;i++){
        s=(struct ListNode*)malloc(sizeof(struct ListNode));
        s->val=result[i];
        r->next=s;
        r=s;
    }
    r->next=NULL;
    l3=l3->next;
    return l3;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值