[LeetCode]2. Add two num

博客围绕 LeetCode 第 2 题展开,题目是给定两个代表非负数的链表,求这两个数的和。例如 (2 -> 4 -> 3) 与 (5 -> 6 -> 4) 代表的 342 和 465 相加得 807,结果链表为 7 -> 0 -> 8,解题时需注意进位。

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

LeetCode 2. Add two num

内容描述

给定两个链表代表两个非负数,求这两个数的和
(2 -> 4 -> 3) + (5 -> 6 -> 4)
因为 342 + 465 = 807
所以返回 7 -> 0 -> 8

注意进位!

class ListNode {
public:
    int val;
    ListNode *next;

    ListNode() {}

    ListNode(int val1) : val(val1), next(NULL) {

    }
};

ListNode add_two_nums(ListNode *l1, ListNode *l2) {

    ListNode ret(0);
    ListNode *current = &ret;
    int carry = 0;
    while (l1 && l2) {
        int dig=l1->val +l2-> val +carry;
        int val=dig%10;
        carry=dig/10;
        ListNode *newNode=new ListNode(val);
        current->next=newNode;
        current=current->next;
        l1=l1->next;
        l2=l2->next;
    }
    if(l2){
        l1=l2;
    }
    while(l1){
        int val=(l1->val+carry)%10;
        carry=(l1->val+carry)/10;
        current->next=new ListNode(val);
        current=current->next;
        l1=l1->next;
    }

    // do not forget!
    if(carry!=0){
        current->next=new ListNode(carry);
    }

    return ret;


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值