LeetCode | Add Two Numbers

本文介绍了解决LeetCode上“两数相加”问题的思路与代码实现。该题要求将两个以逆序存储的非负整数链接列表相加,并返回结果作为一个链接列表。文章详细解释了如何处理不同长度的列表以及进位问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


题外话:圣诞快乐!近期工作告一段落,内心强烈渴望一段规律充实的自主学习生活。哇哈哈哈所以我又来更博了~


没想到上一次刷题已经变得那么久远,对于Leetcode这个OJ平台还是不太熟悉,再加上C++学得不好。。。总之,要努力的地方还有很多啊!今天写了第二题,以此文整理一下做题思路。


题意:

2. Add Two Numbers

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

翻译过来就是输入两串非负的数字,十进制以倒叙的方式存储,意味着排练顺序是:个 十 百 千 万 ... 要求输出两串数串的加和串。

解题方案:

顺着题意进行思考,

如果两个串长度一致,则直接累加,须留意最后一位的进位项,如果有则需要生成新的节点存储数据。

如果两个串长度不一致,那么需要留意两个串长度的比较方式,刚开始想到的比较麻烦的做法是:遍历一遍两个数串,选出比较短的那一串进行操作,然后将剩余较长串的数字直接保留,但需要处理进位项和长串的关系,思路出现一些混乱。

普世化做法,两个数串相加,如果出现一长一短,则说明短的那一数串当前位为0,则只需要将短串用0补齐则能够像同样长度数串情况处理。


代码:

/**
 * 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) {
        ListNode* result = new ListNode(0);
        // if l1 and l2 are pointing to NULL
        if( l1 == NULL && l2 == NULL )
            return result;
        
        int sum = 0, carry = 0, val1, val2;
        ListNode* p = result;
        // if one of these 2 links not reaching the end
        while( l1 != NULL || l2 != NULL )
        {
            if( l1 == NULL )
                val1 = 0;
            else
                val1 = l1->val;
            if( l2 == NULL )
                val2 = 0;
            else
                val2 = l2->val;
            sum = val1 + val2 + carry;
            carry = sum / 10;
            p->next = new ListNode( sum % 10 );
            p = p->next;
            if( l1 != NULL )
                l1 = l1->next;
            if( l2 != NULL )
                l2 = l2->next;
        }
        // peocess the carry number
        if( carry != 0 )
        {
            p->next = new ListNode( carry );
        }
        
        return result->next;
        
    }
};

实话说,还是挺惭愧的,因为对指针的操作和类内定义不清晰,所以初始阶段编程的时候因为初始化就闹了不少笑话。要好好学习才行啊!

另外,Leetcode人性化的一点是不需要考虑输入和输出,只需要写中间的处理函数即可。


题外话ending:今天就到这~年末了,多加衣服多喝水,加油加油!




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值