【中等】2-两数相加 Add Two Num

时间:2020-04-14
本文章向大家介绍【中等】2-两数相加 Add Two Num,主要包括【中等】2-两数相加 Add Two Num使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

题目

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

输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807

来源:力扣(LeetCode)
链接:https://leetcode.com/problems/add-two-numbers

解题思路

首先,很明显这道题是要我们同时遍历两个链表,将两个链表同序号的元素相加作为新的值,同时需要注意的两点是进位问题和两个链表长度不一致的问题。

对于进位问题,我们只需要使用一个add变量来存储每一步的进位,并在下一步计算时添加这个add即可,也就是新一位数字 = (add + l1 + l2) % 10 add = (add + l1 + l2) / 10

对于链表长度不一致问题,问题在于链表l1和l2到达NULL的位数可能不一致,但是无论l1和l2是否一致到达NULL,公式新一位数字 = (add + l1 + l2) % 10永远是成立的,只是l1和l2的值是否为0的区别,也就是说结果的位数是否停止,取决于add、l1、l2三个变量,当三个变量都无效时,计算才停止。

代码

class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode res(0), *curr = &res;
        int add = 0;
        while (l1 or l2 or add) {
            int tmp = flag;
            ListNode *next = l1 ? l1 : l2;
            if (l1 != nullptr) {
                tmp += l1->val;
                l1 = l1->next;
            }
            if (l2 != nullptr){
                tmp += l2->val;
                l2 = l2->next;
            }
            
            add = tmp / 10;
            tmp %= 10;
            
            if (next == nullptr) next = new ListNode(tmp);
            next->val = tmp;

            curr->next = next;
            curr = curr->next;
        }
        return res.next;
    }
};

原文地址:https://www.cnblogs.com/suata/p/12699711.html