天天看点

LeetCode0002两数相加

题目描述

LeetCode0002两数相加

python3解法

class Solution:
    def addTwoNumbers(self, l1, l2):
        re = ListNode(0)
        r=re
        carry=0
        while(l1 or l2):
            x= l1.val if l1 else 0
            y= l2.val if l2 else 0
            s=carry+x+y
            carry=s//10
            r.next=ListNode(s%10)
            r=r.next
            if(l1!=None):l1=l1.next
            if(l2!=None):l2=l2.next
        if(carry>0):
            r.next=ListNode(1)
        return re.next
           

javascript解法

var addTwoNumbers = function(l1, l2) {
    
    let result;
    let cache = [];
    let flag = 0;
    
    while(l1 || l2) {
        let sum = (l1 ? l1.val : 0) + (l2 ? l2.val : 0) + flag;
        if (sum > 9) {
            sum -= 10;
            flag = 1;
        } else {
            flag = 0;
        }
        
        let list = new ListNode(sum);
        if (cache[0]) {
            cache[0].next = list;
            cache[0] = list;
        } else {
            cache[0] = result = list;
        }    
        
        l1 = l1 && l1.next;
        l2 = l2 && l2.next;
    }
    
    if (flag === 1) {
        cache[0].next = new ListNode(1);
    }
    return result; 
};
           

C++解法

ps:终于到我最喜欢的C++啦

class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode* dummy=new ListNode(0);
        ListNode* curr=dummy;
        int carry=0;
        while(l1||l2){
            int val1=l1? l1->val:0;
            int val2=l2? l2->val:0;
            int sum=val1+val2+carry;
            carry=sum/10;
            curr->next=new ListNode(sum%10);
            curr=curr->next;
            if(l1) l1=l1->next;
            if(l2) l2=l2->next;
        }
        if(carry) curr->next=new ListNode(carry);
        return dummy->next;
    }
};
           

可以自己复制代码到leetcode中提交一下

也可以从GitHub地址中git clone下来

GitHub地址