美文网首页
2. Add Two Numbers

2. Add Two Numbers

作者: JamesLivin | 来源:发表于2018-06-20 05:49 被阅读0次

    Problem

    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 contains 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.
    Example

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

    Solution

    Elementary Math/基础数学

    通过从链表头部开始模拟每一位数字的求和,来获得进位数值。
    如同在纸上进行计算时一样,我们从最低有效位开始求和,即l1和l2的头部。由于每一位的数值范围是0到9,求和可能会溢出。此时,我们只保留个位数,将进位记为1,并且参加下一位的计算。在十进制加法中,进位只可能是0或者1。

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode dummyHead = new ListNode(0);
        ListNode p = l1, q = l2, curr = dummyHead;
        int carry = 0;
        while (p != null || q != null) {
            int x = (p != null) ? p.val : 0;
            int y = (q != null) ? q.val : 0;
            int sum = carry + x + y;
            carry = sum / 10;
            curr.next = new ListNode(sum % 10);
            curr = curr.next;
            if (p != null) p = p.next;
            if (q != null) q = q.next;
        }
        if (carry > 0) {
            curr.next = new ListNode(carry);
        }
        return dummyHead.next;
    }
    

    复杂度分析

    • 时间复杂度:O(max(m,n))。假设m和n表示链表l1和l2的长度,上述的算法最多循环max(m,n)次。
    • 空间复杂度:O(max(m,n))。新链表的最大长度是max(m,n) + 1。

    相关文章

      网友评论

          本文标题:2. Add Two Numbers

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