zoukankan      html  css  js  c++  java
  • Add Two Numbers

    题目链接

    Add Two Numbers - LeetCode

    注意点

    • 考虑位数不一样的情况以及首位有进位的情况

    解法

    解法一:模拟加法,用变量carry保存进位。遍历链表,先算长度相同的部分,然后算长度多出来的那部分,随时要更新carry的值。最后判断carry的值因为会有首位进位的情况。时间复杂度为O(n)

    /**
     * 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 carry = 0;
            ListNode* anw = new ListNode(carry);
            ListNode* pointer = anw;
            while(l1 != NULL && l2 != NULL)
            {
                pointer->next = new ListNode((carry+l1->val+l2->val)%10);
                pointer = pointer->next;
                carry = (carry+l1->val+l2->val)/10;
                l1 = l1->next;
                l2 = l2->next;
            }
            while(l1 != NULL)
            {
                pointer->next = new ListNode((carry+l1->val)%10);
                pointer = pointer->next;
                carry = (carry+l1->val)/10;
                l1 = l1->next;
            }
            while(l2 != NULL)
            {
                pointer->next = new ListNode((carry+l2->val)%10);
                pointer = pointer->next;
                carry = (carry+l2->val)/10;
                l2 = l2->next;
            }
            if(carry != 0)
            {
                pointer->next = new ListNode(carry);
                pointer = pointer->next;
            }
            return anw->next;
        }
    };
    }
    

    小结

    • 以前做过类似的题目,所以一下就有思路了,就是链表的使用想了好一会...
  • 相关阅读:
    NOIP2020 游记
    李超线段树
    选举「elections」
    Alt+数字输入
    素数
    CSP-S2020 爆炸记
    [CF487C] Prefix Product Sequence
    [CF489E] Hiking
    L2-019 悄悄关注 (25 分)
    L2-032 彩虹瓶 (25 分)
  • 原文地址:https://www.cnblogs.com/multhree/p/10290760.html
Copyright © 2011-2022 走看看