算法分析與設計——LeetCode Problem.2 Add Two Numbers

問題詳情

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.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8


問題分析與思路

問題中要求按照順序將兩列數字相加,並且每列中的數字一次只能有一位,並向後進位。
並且題目已經給出部分代碼框架如下

/**
 * 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) {
};

由此框架我得出的思路是將兩個整數表示爲鏈表,然後從第一位(個位)開始依次相加,並且將得出的數取出個位數放進新的鏈表中,然後將得出的數的十位用於下一位加法。
值得注意的是有可能出現類似一個鏈表有三位,一個有兩位的情況,所以我使用了一個while來判斷兩個鏈表是否同時爲null,同時我使用了判斷語句?:來檢驗兩個鏈表是否爲空並且定義他的值。


編程中遇到的問題

解決問題時我忽略了最後一位的加法的進位,因此fail了,於是我在while外面又加了幾行代碼,輕鬆解決問題。
另外我使用同一代碼,運行時間一次擊敗了百分之七的代碼,一次擊敗了百分之44的代碼,運行時間相差近一倍。我覺得這應該與網速和電腦速度有關?


具體代碼

class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode *l3 = new ListNode(0);
        int carry = 0;
        int sum;
        ListNode *l4 = l3;
        while(l1 != NULL || l2 != NULL) {
            sum = (l1 ? l1->val : 0) + (l2 ? l2 -> val : 0) + carry;
            l4 -> next = new ListNode(sum % 10);
            carry = sum / 10;
            l1 = l1? l1->next : l1;
            l2 = l2? l2->next : l2;
            l4 = l4 -> next;
        }
        if (carry > 0) {
            l4->next = new ListNode(carry);
        }
        return l3->next;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章