首页 > 技术文章 > 【leetcode】Add_Two_Numbers

LemonSqueezz 2021-01-05 00:11 原文

题干

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.

展开查看翻译

给出两个非空的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。

如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。

您可以假设除了数字 0 之外,这两个数都不会以 0 开头。

Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

来源:力扣(LeetCode)

题解

题意:输入两端逆序的列表,逐位相加后输出一个逆序的结果。实质为简单加减法

⚠️注意事项: 1⃣️十进制加减法逢十进一2⃣️两个数长度不一的情况3⃣️两个数中存在0的情况4⃣️即使两个链表都不存在下一位,若有进位,则仍需要计算

源码:

/**
 * 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) {
        int sum = l1->val + l2->val;
        ListNode* l3 = new ListNode(sum % 10);
        ListNode* p = l3;
        sum = sum / 10;
        while(l1->next||l2->next||sum){
            if(l1->next){
                l1 = l1->next;
                sum = sum + l1->val;
            }
            if(l2->next){
                l2 = l2->next;
                sum = sum + l2->val;
            }
            p->next = new ListNode(sum % 10);
            p = p->next;
            sum = sum / 10;
        }
        return l3;
    }
};

推荐阅读