zoukankan      html  css  js  c++  java
  • [LeetCode] 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.
    

    用加法合并两个单链表

    开始我想把l2合并到l1去,发现我搞不定,于是把l1 l2合并到一个新的链表中去,下面是第一个版本

    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        if (! (l1 && l2))
        {
            return l1 ? l2: l1;
        }
    
        int carry = 0;
    
        ListNode* root = new ListNode(l1->val + l2->val);
        carry = root->val / 10;
        root->val %= 10;
    
        ListNode* l3 = root;
    
        l1 = l1->next;
        l2 = l2->next;
    
        while (l1 || l2)
        {
            int v1 = l1 ? l1->val : 0;
            int v2 = l2 ? l2->val : 0;
    
            ListNode* tmp = new ListNode(v1 + v2 + carry);
            carry = tmp->val / 10;
            tmp->val %= 10;
            root->next = tmp;
            root = root->next;
    
            l1 = l1 ? l1->next : NULL;
            l2 = l2 ? l2->next : NULL;
        }
    
        if (carry != 0) //l1 l2都没了,但有进位,需加一个ListNode
        {
            ListNode * tmp = new ListNode(1);
            root->next = tmp;
        }
    
        return l3;
    }
    

    我看了LeetCode上最好的那份代码,比我的好多了,于是新的代码如下(copy & paste)

    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        int carry = 0;
        ListNode *root = nullptr, *l3 = nullptr;
    
        while (l1 || l2 || carry)
        {
            if (l1)
            {
                carry += l1->val;
                l1 = l1->next;
            }
    
            if (l2)
            {
                carry += l2->val;
                l2 = l2->next;
            }
    
            if (l3)
            {
                l3->next = new ListNode(carry % 10);
                l3 = l3->next;
            }
            else
            {
                root = new ListNode(carry % 10);
                l3 = root;
            }
    
            carry /= 10;
        }
    
        return root;
    }
    
  • 相关阅读:
    C++STL中的unique函数解析
    STL中erase()的用法
    刷题技巧——简易哈希表的实现
    经典面试题目——找到第n个丑数(参考《剑指offer(第二版)》面试题49)
    C++中sort函数小结
    谈谈交叉验证法(个人小结)
    数字序列中某一位数字(《剑指offer》面试题44)
    求1~n整数中1出现的次数(《剑指offer》面试题43)
    2018年美团春招(第二批)题解
    C/C++中字符串和数字互转小结
  • 原文地址:https://www.cnblogs.com/arcsinw/p/9504301.html
Copyright © 2011-2022 走看看