Leetcode-2Add Two Numbers

2. Add Two Numbers

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.

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

Example

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

題解:(方法不好,待優(yōu)化)

將兩個(gè)數(shù)以逆序(從左到右對(duì)應(yīng)低位到高位)存入兩個(gè)鏈表,然后將兩個(gè)數(shù)求和的結(jié)果逆序存入新的鏈表中輸出。
來(lái)個(gè)炒雞無(wú)腦的解題思路,首先創(chuàng)建一個(gè)頭結(jié)點(diǎn),讓指針l指向該頭結(jié)點(diǎn)地址;int bit = 0用來(lái)表示是否進(jìn)位,有進(jìn)位則將bit值賦為1;將鏈表各節(jié)點(diǎn)值加上進(jìn)位求和,再對(duì)10取余得到新的節(jié)點(diǎn)值;用新的節(jié)點(diǎn)值替換其中一個(gè)鏈表l1的節(jié)點(diǎn)值,進(jìn)而通過l->next = l1將該位求和后的值連接在新鏈表中,直到原來(lái)的兩個(gè)鏈表中有一個(gè)為空;將剩余的鏈表對(duì)應(yīng)的各節(jié)點(diǎn)值和對(duì)應(yīng)的進(jìn)位值求和后對(duì)10取余獲得新的節(jié)點(diǎn)值,連接到新鏈表的結(jié)尾。

My Solution(C/C++完整實(shí)現(xiàn)):

#include <cstdio>
#include <iostream>

using namespace std;

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
    ListNode * addTwoListNumber(ListNode *l1, ListNode *l2) {
        ListNode result(0);
        ListNode *l = &result;
        int bit = 0;
        int sum;
        while(l1 && l2) {
            sum = l1->val + l2->val + bit;
            l1->val = sum % 10;
            bit = sum / 10;
            l->next = l1;
            l1 = l1->next;
            l2 = l2->next;
            l = l->next;
        }
        while (l1) {
            sum = l1->val + bit;
            l1->val = sum % 10;
            bit = sum / 10;
            l->next = l1;
            l1 = l1->next;
            l = l->next;
        }
        while (l2) {
            sum = l2->val + bit;
            l2->val = sum % 10;
            bit = sum / 10;
            l->next = l2;
            l2 = l2->next;
            l = l->next;
        }
        if (bit == 1) {
            l->next = new ListNode(1);  //為值為1的節(jié)點(diǎn)分配內(nèi)存空間
        }
        return result.next;
    }
};

int main() {
    ListNode a1(2);
    ListNode b1(4);
    ListNode c1(3);
    ListNode a2(5);
    ListNode b2(6);
    ListNode c2(4);
    a1.next = &b1;
    b1.next = &c1;
    a2.next = &b2;
    b2.next = &c2;
    Solution s;
    ListNode *result = s.addTwoListNumber(&a1, &a2);
    while (result) {
        printf("%d->", result->val);
        result = result->next;
    }
    return 0;
}

結(jié)果:

7->0->8->

My Solution(Python):

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

class Solution:
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        l = ListNode(0)
        result = l
        bit = 0
        while l1 and l2:
            l1.val, bit = (l1.val + l2.val + bit) % 10, (l1.val + l2.val + bit) // 10
            l.next = l1
            l1, l2, l = l1.next, l2.next, l.next
        while l1:
            l1.val, bit = (l1.val + bit) % 10, (l1.val + bit) // 10
            l.next = l1
            l1, l = l1.next, l.next
        while l2:
            l2.val, bit = (l2.val + bit) % 10, (l2.val + bit) // 10
            l.next = l2
            l2, l = l2.next, l.next
        if bit == 1:
            l.next = ListNode(1)
        return result.next

Reference:

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

class Solution:
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        carry = 0
        root = n = ListNode(0)
        while l1 or l2 or carry:
            v1 = v2 = 0
            if l1:
                v1 = l1.val
                l1 = l1.next
            if l2:
                v2 = l2.val
                l2 = l2.next
            carry, val = divmod(v1+v2+carry, 10)
            n.next = ListNode(val)
            n = n.next
        return root.next
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容