×

100DaysLeetcode(1)

96
叶孤城___
2018.04.08 01:23 字数 61

Add Two Numbers

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
Explanation: 342 + 465 = 807.

Solution

public class ListNode {
  public var val: Int
  public var next: ListNode?
  public init(_ val: Int) {
    self.val = val
    self.next = nil
  }
}

class AddTwoNumbers {
  func addTwoNumbers(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
    if l1 == nil, l2 == nil {
      return nil
    }
    
    var l1 = l1, l2 = l2
    var carry = 0
    let link = ListNode(0)
    var nextNode = link
    while l1 != nil || l2 != nil {
      let sum = (l1?.val ?? 0) + (l2?.val ?? 0) + carry
      carry = sum/10
      nextNode.val = sum%10
      l1 = l1?.next
      l2 = l2?.next
      if l1 == nil, l2 == nil {
        if carry > 0 {
          let node = ListNode(1)
          nextNode.next = node
          break
        }
      }else {
        let node = ListNode(0)
        nextNode.next = node
        nextNode = node
      }
    }
    return link
  }
}
日記本
Web note ad 1