【LeetCode】2. Add Two Numbers 解題報告(Python & C++)

做者: 負雪明燭
id: fuxuemingzhu
我的博客: http://fuxuemingzhu.cn/node


題目地址:https://leetcode.com/problems/add-two-numbers/description/python

題目描述

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.git

You may assume the two numbers do not contain any leading zero, except the number 0 itself.面試

Example:ide

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

題目大意

有兩個鏈表,分別是逆序了的十進制數字。如今要求兩個十位數字的和,要求返回的結果也是鏈表。spa

解題方法

偷懶作法

先求和,再構建鏈表。這個方法比較暴力。指針

# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None

class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """
        num1 = ''
        num2 = ''
        while l1:
            num1 += str(l1.val)
            l1 = l1.next
        while l2:
            num2 += str(l2.val)
            l2 = l2.next
        add = str(int(num1[::-1]) + int(num2[::-1]))[::-1]
        head = ListNode(add[0])
        answer = head
        for i in range(1, len(add)):
            node = ListNode(add[i])
            head.next = node
            head = head.next
        return answer

模擬加法

根據官方solution的方法,能夠採用一個進位carry方便的完成一次遍歷得出結果,不過過程稍微麻煩。code

此處輸入圖片的描述

兩個要注意的地方:若是列表長度不相等;若是列表相加完成最後仍有進位位。遞歸

# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None

class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """
        head = ListNode(0)
        answer = head
        carry = 0
        while l1 and l2:
            add = l1.val + l2.val + carry
            carry = 1 if add >= 10 else 0
            head.next = ListNode(add % 10)
            head = head.next
            l1, l2 = l1.next, l2.next
        l = l1 if l1 else l2
        while l:
            add = l.val + carry
            carry = 1 if add >= 10 else 0
            head.next = ListNode(add % 10)
            head = head.next
            l = l.next
        if carry:
            head.next = ListNode(1)
        return answer.next

使用C++代碼以下,這裏在while循環中作了判斷,若是l1,l2,carry等有一個存在那麼就在後面繼續添加節點,若是l1或者l2不存在就把它的值當作0處理。須要注意的是,下面的代碼作了new操做,可是沒有釋放dummy指針,形成了內存泄露,雖然刷題能過,可是面試的時候應該會被面試官懟。C++須要本身管理內存,當須要new操做的時候,仍是當心爲妙啊!圖片

/** * 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* dummy = new ListNode(0);
        ListNode* cur = dummy;
        int carry = 0;
        while (l1 || l2 || carry) {
            int target = (l1 ? l1-> val : 0) + (l2 ? l2-> val : 0) + carry;
            if (target >= 10) {
                carry = 1;
                target -= 10;
            } else 
                carry = 0;
            cur->next = new ListNode(target);
            cur = cur->next;
            if (l1)
                l1 = l1->next;
            if (l2)
                l2 = l2->next;
        }
        return dummy->next;
    }
};

遞歸解法

這個題的遞歸解法也是很是好玩的,若是兩個鏈表節點都存在的話,把兩個節點的值相加而且模10做爲當前的結果,同時若是這個結果>=10須要把它的next節點+1.

這個解法妙在自然地處理好了兩個鏈表不同長、最終相加結果有進位的狀況。

/** * 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) {
        if (!l1) return l2;
        if (!l2) return l1;
        int target = l1->val + l2->val;
        ListNode* res = new ListNode(target % 10);
        res->next = addTwoNumbers(l1->next, l2->next);
        if (target >= 10)
            res->next = addTwoNumbers(res->next, new ListNode(1));
        delete l1, l2;
        return res;
    }
};

日期

2018 年 2 月 26 日 2019 年 1 月 11 日 —— 小光棍節?

相關文章
相關標籤/搜索