leetcode 题解 2. Add Two Numbers

leetcode的第二题,这一题实际上已经将问题做了简化,链表已经进行了逆序,因此只要从后向前处理即可。

这里有几点需要注意的问题:

两个数相加后结果可能大于10,因此需要主要进位的问题。

两个链表的长度可能不同,若一个链表为空,则将其值设为0。

若最后的结果仍然大于10,则还要再进一位。

直接将结果贴出来。

struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
    if(l1==NULL) return l2;
    if(l2==NULL) return l1;
    int add = 0;
    int sum = 0;
    int tempSum = 0;
    int l1val = 0;
    int l2val = 0;
    struct ListNode* result = (struct ListNode*)malloc(sizeof(struct ListNode));
    struct ListNode* cur = result;
    struct ListNode* nxt;
    struct ListNode* pre;
    while(l1!=NULL||l2!=NULL){
        if(l1) l1val = l1->val;
        else l1val = 0;
        if(l2) l2val = l2->val;
        else l2val = 0;
        tempSum = l1val + l2val + add;
        sum = tempSum%10;
        add = tempSum/10;
        cur->val = sum;
        if(l1!=NULL) l1 = l1->next;
        if(l2!=NULL) l2 = l2->next;
        nxt = (struct ListNode*)malloc(sizeof(struct ListNode));
        cur->next = nxt;
        pre = cur;
        cur = nxt;
    }
    if(add!=0){
        cur->val = add;
        pre = cur;
    }
    pre->next = NULL;
    return result;
    
}


贴一段java代码,简洁很多,上面的C代码过于复杂了。

class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if(l1==null) return l2;
        if(l2==null) return l1;
        
        ListNode list_result = new ListNode(-1);
        ListNode list_pointer = list_result;
        
        int sum = 0;
        
        while(l1!=null||l2!=null){
            
            if(l1!=null){
                sum += l1.val;
                l1 = l1.next;
            }
            
            if(l2!=null){
                sum += l2.val;
                l2 = l2.next;
            }
            
            list_pointer.next = new ListNode(sum%10);
            sum = sum/10;
            list_pointer = list_pointer.next;
        }
        
        if(1==sum) list_pointer.next = new ListNode(1);
        
        return list_result.next;
        
    }
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值