LeetCode 2 - Add Two Numbers

一、问题描述

Description:

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

给定两个链表,代表两个非负整数。链表的每个节点包含该整数的一个位上的数字,并且是逆序存储。例如:输入2 -> 4 -> 35 -> 6 -> 4,342 + 465 = 807,故输出7 -> 0 -> 8


二、解题报告

思路:由于链表从头到尾依次存放的个位、十位、百位……根据加法的计算方法,每次把对应的位(结点)相加以后,若大于等于10,则进位 …… 依次类推。

下面上代码:

/**
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        return add(l1, l2, 0);
    }

    ListNode* add(ListNode* l1, ListNode* l2, int carry) {
        if(l1==NULL && l2==NULL && carry==0)  // 递归终止条件
            return NULL;

        int sum = carry;  // 对应的两个位相加,并且加上进位
        if(l1!=NULL) sum += l1->val;
        if(l2!=NULL) sum += l2->val;

        ListNode* result = new ListNode(0);  // 新建一个结点
        result->val = sum%10;
        result->next = add(l1==NULL?NULL:l1->next, 
                           l2==NULL?NULL:l2->next, 
                           sum>=10?1:0);

        return result;
    }
};





LeetCode答案源代码:https://github.com/SongLee24/LeetCode


转载于:https://www.cnblogs.com/songlee/p/5738069.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值