美文网首页
2. Add Two Numbers

2. Add Two Numbers

作者: RobotBerry | 来源:发表于2017-04-29 09:42 被阅读0次

问题

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.

输入

(2 -> 4 -> 3) + (5 -> 6 -> 4)

输出

7 -> 0 -> 8

分析

两个链表相加,生成一个和链表。同步遍历两个链表,算出当前两个节点的和sum,把sum%10插入到和链表中,把sum/10作为carry加入到下一步的sum计算。

要点

简单的按位相加,要考虑到链表的结尾以及carry的处理。

时间复杂度

O(max(m,n)),m和n分别为输入两个链表的长度。

空间复杂度

O(1)

代码

/**
 * 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 *l3 = new ListNode(-1);
        ListNode *pl3 = l3;
        
        int carry = 0;
        while (l1 || l2 || carry) {
            int sum = carry;
            if (l1 != NULL) {
                sum += l1->val;
                l1 = l1->next;
            }
            if (l2 != NULL) {
                sum += l2->val;
                l2 = l2->next;
            }
            
            carry = sum / 10;
            ListNode *tmp = new ListNode(sum % 10);
            pl3->next = tmp;
            pl3 = tmp;
        }

        return l3->next;
    }
};

相关文章

网友评论

      本文标题:2. Add Two Numbers

      本文链接:https://www.haomeiwen.com/subject/wflzzttx.html