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


posted @ 2015-05-11 22:21  神奕  阅读(119)  评论(0编辑  收藏  举报