LeetCode題解:Add Two Numbers

LeetCode題解

說明:本人不是什麼算法高手,部份內容參考了Google、stackoverflow、segmentfault中獲得的一些解答或者代碼。之因此去作Leetcode上的題是由於畢業工做後對算法有了新的認知。工做時發現雖然不是全部的算法都用獲得,有些算法也已經封裝好了只須要調用API就能夠了。可是在有些時候當你不得不本身寫算法的時候,你就會發現算法重要性,它不只能讓你很好的解決問題並且對你解決一塊兒其它問題帶來一些很好的思路的引導,如下代碼都測試經過。node

Add Two Numbers:

You are given two linked lists representing two non-negative numbers. 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.

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

題目的意思就是:就兩個表明非負數字的鏈表。鏈表中的數字是逆序存儲的,每一個結點存儲一位數字。把兩個鏈表數字相加,而後把結果以相同的形式出現。例子中是兩個分別表明342和465的鏈表,相加後爲807將相加的結果以相同的形式鏈表表示。算法

解決方法:

根據原題的意思,能夠很快的找到解決方法。咱們先將兩個鏈表的數字還原,而後獲得兩個的和。將獲得的和用取餘運算從低位到高位採用尾插入法獲得相同形式的鏈表,代碼以下:segmentfault

/*
 //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) {
        int nFirst = 0,nSecond = 0,nSum = 0 ,nValue = 0,nStart = 0, nLength = 0;
        ListNode *node = NULL,*head = NULL,*temp=NULL;
        string    strSum;
    
        nFirst  = GetOriginalValue(l1);
        nSecond = GetOriginalValue(l2);
        nSum = nFirst + nSecond;
        strSum = to_string(nSum);
        nLength = strSum.length();
    
        for(nStart = 0;nStart<nLength;nStart++)
        {
            nValue = nSum % 10;
            node = new ListNode(nValue);
            if(head != NULL)
            {
                temp->next = node;
                temp = temp->next;
            }
            else
            {
                head = node;
                temp = head;
            }
            node = NULL;
            nSum /= 10;
        }
        return head;        
    }
    
private:
    int    GetOriginalValue(ListNode *l)
    {
        int x = 0,nLength=0,temp=0;
        while (l != NULL){
            temp = pow(10,nLength) * l->val;
            x += temp ;
            l = l->next;
            nLength++;
        }
        return x;
    }
};
相關文章
相關標籤/搜索