LeetCode系列:2 Add Two Numbers

版权声明:书写博客,不为传道受业,只为更好的梳理更好的记忆,欢迎转载与分享,更多博客请访问:http://blog.csdn.net/myinclude 和 http://www.jianshu.com/u/b20be2dcb0c3 https://blog.csdn.net/myinclude/article/details/83752590

Q:You are given two non-empty linked lists representing two nonnegative 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.


Example:

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

E:给定两个非空链表代表两个非负整数,这两个数字被逆序存储并且他们的每一个节点只存一个单一数字,返回这两个数字加起来组合成的新链表。

你可以假设这两个数字不是0开头,除了0它自己

e.g.
输入:
链表1(2 -> 4 -> 3) 链表2(5 -> 6 -> 4)
因为342 + 465=807,所以
输出:
新链表:
7 -> 0 -> 8

A:

Approach:

因为链表存储顺序刚好和我们做加法的顺序一致,所以我们只需要按照正常数学加法来操作这两个数字即可。
每次拿链表1和链表2的一个元素相加,这个时候可能会有几种情况:
a、链表1和链表2长度不相等,此时取值一个能取,一个已经没有了;
b、链表1和链表2相加,有进位;
c、链表其中一个没有元素,一个还有元素且此时还有进位,需要元素与进位相加;
d、都没有元素,但是此时还有进位。

class Solution {
    func addTwoNumbers(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
        
        let header = ListNode(0) 
        var list1 = l1, list2 = l2, carry = 0, tempNode = header
        while list1 != nil || list2 != nil || carry != 0 {//考虑上面提到的a,b,c,d四种情况
            if list1 != nil {
                carry += list1!.val
                list1 = list1?.next
            }
            if list2 != nil {
                carry += list2!.val
                list2 = list2?.next
            }
            tempNode.next = ListNode(carry%10)
            tempNode = tempNode.next!
            carry /= 10	//获取进位,如果没有,则为0

        }
        return header.next//因为一开始实例化的是ListNode(0) ,所以要从下一个开始,不然会多一个0元素
    }
}
Complexity Analysis:
  • 时间复杂度: O(n)。(LeetCode:64 ms)
  • 空间复杂度:O(n)。

猜你喜欢

转载自blog.csdn.net/myinclude/article/details/83752590