zoukankan      html  css  js  c++  java
  • LeetCode #2 Add Two Numbers

    LeetCode #2 Add Two Numbers

    Question

    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.

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

    Output: 7 -> 0 -> 8

    Solution

    Approach #1

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     public var val: Int
     *     public var next: ListNode?
     *     public init(_ val: Int) {
     *         self.val = val
     *         self.next = nil
     *     }
     * }
     */
    class Solution {
        func addTwoNumbers(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
            var sum = 0
            let head = ListNode(0)
            var node: ListNode? = head
            var p = l1
            var q = l2
            while p != nil || q != nil {
                if let pVal = p?.val {
                    sum += pVal
                    p = p?.next
                }
                if let qVal = q?.val {
                    sum += qVal
                    q = q?.next
                }
                node?.next = ListNode(sum % 10)
                node = node?.next
                sum /= 10
            }
            if sum > 0 { node?.next = ListNode(sum) }
            return head.next
        }
    }
    

    Assume that m and n represents the length of l1 and l2 respectively.

    Time complexity: O(max(m, n)).

    Space complexity: O(max(m, n)).

    转载请注明出处:http://www.cnblogs.com/silence-cnblogs/p/6848514.html

  • 相关阅读:
    Codeigniter 控制器的继承问题
    laravel 安装
    js preventDefault() 方法
    jquery 获取$("#id").text()里面的值 需要进行去空格去换行符操作
    HDU_1394_线段树
    Codeforces_723_D
    Codeforces_723_C
    Codeforces_723_B
    Codeforces_723_A
    HDU_4456_二维树状数组
  • 原文地址:https://www.cnblogs.com/silence-cnblogs/p/6848514.html
Copyright © 2011-2022 走看看