[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;
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,858评论 0 33
  • 窗外的雨声 滴答 滴答 独倚窗前 雨落下的痕迹 是你的背影 夜无风 月独影 心有殇 残缺的夜是思念 无边的黑暗是轮...
    浅笑不离殇阅读 267评论 6 5
  • 人心都难测,活得像鬼。
    山河永寂的长情阅读 297评论 0 0
  • 今天下午,我写完作业后,好友邀我去打篮球,我满心欢喜地答应了。 来到熟悉的篮球场,我开始投篮了。我举起球,对准篮球...
    章鱼去哪儿阅读 286评论 0 2
  • 3月18号,回南潮湿的天气,早上还飘着零星小雨,但这并不能阻挡一群爱故事爱学习爱孩子的妈妈们的热情。因为今天彩虹花...
    大白菜和小乖乖阅读 1,112评论 0 0

友情链接更多精彩内容