Leetcode 2. 两数相加

这道题让我想起了acwing里的高精度加法,因为这里的加法也是超过100位了。于是套着模板写了一下,然后看了一下评论区,发现链表再套vector属于是脱裤子放屁了

复制代码
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
 #include <vector>
class Solution {
public:

    vector<int> add(vector<int> &a, vector<int> &b){
        int t = 0;
        vector<int> c;
        for(int i = 0; i < a.size() || i < b.size(); i ++ ){
            if(i < a.size()) t += a[i];
            if(i < b.size()) t += b[i];
            c.push_back(t % 10);
            t /= 10;
        }
        if(t) c.push_back(1);
        return c;
    }

    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        vector<int> A, B;
        while(l1 != nullptr){
            A.push_back(l1->val);
            l1 = l1->next;
        }
        while(l2 != nullptr){
            B.push_back(l2->val);
            l2 = l2->next;
        }
        
        vector<int> c;
        c = add(A, B);

        ListNode *l3 = new ListNode(c[0]);
        ListNode *res = l3;
        int len = c.size();
        for(int i = 1; i < len; i ++ ){
            
            ListNode *next1 = new ListNode(c[i]);
            l3->next = next1;
            l3 = next1;
        }

        return res;
    }
};
复制代码

直接在链表的基础上做,注意和vector不太一样的是,每次加法的循环都要特别注意边界条件,注意两链表指针的更新。

复制代码
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        int t = 0;//存储每一位相加的信息
        
        ListNode *l3 = new ListNode(-1);
        ListNode *res = l3;

        while(l1 != nullptr || l2 != nullptr){
            if(l1 != nullptr){ 
                t += l1->val;
                l1 = l1->next;
            }
            if(l2 != nullptr) {
                t += l2->val;
                l2 = l2->next;
            }
            l3->next = new ListNode(t % 10);
            t /= 10;
            l3 = l3->next;
        }

        if(t) l3->next = new ListNode(1);//如果最后最高位有进位,还得补一个1
        return res->next;
    }
};
复制代码

 

 

  

posted @   luxiayuai  阅读(13)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示