Leetcode 刷题指北 2. Add Two Numbers


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.

解题思路:

1、此题考查用linkedlist模拟加法运算。
2、最直接的想法就是将两个加数恢复成int类型再相加,将结果转换成linkedlist返回。
3、但是int类型允许的整数长度是瓶颈,经过测试发现题目里的测试样例确实有特别长的甚至超过long int类型,那么用意很明显了。
4、只能用linkedlist完全模拟加法运算过程,取数相加,进位,下两位和进位数再相加,处理进位,循环到null...
5、注意:
a. 两个list可能不一样长。
b. 别忘了最后一个非零的进位数。

解题源码:

#include
#include
using namespace std;

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        int sum = l1->val + l2->val;
        int value = sum % 10, c = sum / 10;
        ListNode *res = new ListNode(value);

        ListNode *p1 = l1, *p2 = l2, *pr = res;
        
        while(p1->next != NULL || p2->next != NULL)
        {
            int add_1 = 0, add_2 = 0;
            if (p1->next != NULL) {
                p1 = p1->next;
                add_1 = p1->val;
            }
            if (p2->next != NULL) {
                p2 = p2->next;
                add_2 = p2->val;
            }
            
            sum = add_1 + add_2 + c;
            value = sum % 10, c = sum / 10;
            pr->next = new ListNode(value);
            pr = pr->next;
        }

        if (c != 0) {
            pr->next = new ListNode(c);
        }
        return res;
    }
};

你可能感兴趣的:(Leetcode 刷题指北 2. Add Two Numbers)