[leetcode] 2. Add Two Numbers

Posted zmj97

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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;
    }
};

 


以上是关于[leetcode] 2. Add Two Numbers的主要内容,如果未能解决你的问题,请参考以下文章

2. 两个数相加 [leetcode 2: Add Two Numbers]

2. 两个数相加 [leetcode 2: Add Two Numbers]

LeetCode - 2 - Add Two Numbers

[leetcode][2] Add Two Numbers

[LeetCode]2. Add Two Numbers

LeetCode - 2. Add Two Numbers