[LeetCode] 2.两个数字相加(Add Two Numbers)C++代码实现

1,题目描述

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.

2,题目分析

  1. 新建链表cur
  2. L1,L2两个链表从头到后按位相加,结果插入新链表
  3. 为了避免两个输入链表同时为空,我们建立一个dummy结点,将两个结点相加生成的新结点按顺序加到dummy结点之后,由于dummy结点本身不能变,所以我们用一个指针cur来指向新链表的最后一个结点
  4. 循环条件,只要一个不为空就行,取当前结点值的时候,先判断一下,若为空则取0,否则取结点值。
  5. 然后把两个结点值相加,同时还要加上进位carry。然后更新carry,直接 sum/10 即可,然后以 sum%10 为值建立一个新结点,连到cur后面,然后cur移动到下一个结点
  6. 最高位的进位问题要最后特殊处理一下,若carry为1,则再建一个值为1的结点

3,代码实现

class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode *dummy = new ListNode(-1), *cur = dummy;
        int carry = 0;
        while (l1 || l2) {
            int val1 = l1 ? l1->val : 0;
            int val2 = l2 ? l2->val : 0;
            int sum = val1 + val2 + carry;
            carry = sum / 10;
            cur->next = new ListNode(sum % 10);
            cur = cur->next;
            if (l1) l1 = l1->next;
            if (l2) l2 = l2->next;
        }
        if (carry) cur->next = new ListNode(1);
        return dummy->next;
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

刘大望

谢谢你请的咖啡

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值