[LeetCode]AddTwoNumbers

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 -> 8

Answer:

/**
 * 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) {
        bool m_shouldIncrese = false;
        
        ListNode *m_temp_l1 = l1;
        ListNode *m_temp_l2 = l2;
        int m_l1_length = 0;
        int m_l2_length = 0;
        do{
            m_l1_length++;
            m_temp_l1 = m_temp_l1->next;
        }while(m_temp_l1 != NULL);
        
        do {
            m_l2_length++;
            m_temp_l2 = m_temp_l2->next;
        }while(m_temp_l2 != NULL);
        
        ListNode *m_small;
        ListNode *m_large;
        if (m_l1_length < m_l2_length){
            m_small = l1;
            m_large = l2;
        }
        else{
            m_large = l1;
            m_small = l2;
        }
        ListNode *temp = new ListNode(0);
        ListNode *result = temp;
        do{
            int sum = 0;
            if(m_small != NULL)
            {
                sum = m_large->val + m_small->val + temp->val;
            }
            else{
                sum = m_large->val + temp->val;
            }
            int val = -1;
            if(sum >= 10){
                val = sum - 10;
                m_shouldIncrese = true;
            }
            else{
                val = sum;
                m_shouldIncrese = false;
            }
            temp->val = val;
            m_large = m_large->next;
            if(m_small != NULL)
            {
                m_small = m_small->next;
            }
            if(m_large != NULL || m_shouldIncrese){
                temp->next = new ListNode(0);
                temp = temp->next;
                if (m_shouldIncrese)
                {
                   temp->val = 1; 
                }
            }
        }while(m_large != NULL);
        return result;
    }
};
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問題, 分享了一些自己做題目的經(jīng)驗。 張土汪:刷leetcod...
    土汪閱讀 12,766評論 0 33
  • 窗外的雨聲 滴答 滴答 獨倚窗前 雨落下的痕跡 是你的背影 夜無風 月獨影 心有殤 殘缺的夜是思念 無邊的黑暗是輪...
    淺笑不離殤閱讀 250評論 6 5
  • 人心都難測,活得像鬼。
    山河永寂的長情閱讀 243評論 0 0
  • 今天下午,我寫完作業(yè)后,好友邀我去打籃球,我滿心歡喜地答應(yīng)了。 來到熟悉的籃球場,我開始投籃了。我舉起球,對準籃球...
    章魚去哪兒閱讀 273評論 0 2
  • 3月18號,回南潮濕的天氣,早上還飄著零星小雨,但這并不能阻擋一群愛故事愛學習愛孩子的媽媽們的熱情。因為今天彩虹花...
    大白菜和小乖乖閱讀 1,026評論 0 0