[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.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8


就是简单的高精度加法,刚开始理解错题意WA了好几次。

要注意的是:

判断两个list有没有都算到头;

判断进位是否为0;

考虑有没有多申请节点,最后一个节点不能为0。


以下是我的代码:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode* re = new ListNode(0);
        ListNode* result = re;
        int carry = 0;
        while (l1 || l2 || carry) {
            int tmp = (l1?(l1->val):0) + (l2?(l2->val):0) + carry;
            re->val = tmp % 10;
            carry = tmp / 10;
            if (l1) l1 = l1->next;
            if (l2) l2 = l2->next;
            if (l1 || l2 || carry) re->next = new ListNode(0), re = re->next;
        }
        return result;
    }
};
原文地址:https://www.cnblogs.com/zmj97/p/7526183.html