美文网首页
100DaysLeetcode(1)

100DaysLeetcode(1)

作者: 叶孤城___ | 来源:发表于2018-04-08 01:23 被阅读855次

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
  }
}

相关文章

  • 100DaysLeetcode(1)

    Add Two Numbers You are given two non-empty linked lists ...

  • 100DaysLeetcode(3)

    Longest Substring Without Repeating Characters Given a st...

  • 100DaysLeetcode(2)

    Add Two Numbers Given an array of integers, return indice...

  • 1▪1▪1▪1▪1

    今天是国际劳动节,出门看人头,上路遇堵车,处处挤破头,急哭也停不下车。 不如歇了吧 ...

  • 1+1+1…+1=1

    对“一”的理解: 赠人玫瑰,不仅仅是手留余香。 利益他人,实际上也疗愈了自己。 利他、利己,如此往复循环, 最终利...

  • (-1)×(-1)= 1

    数学家经过很长一段时间才认识到(-1)×(-1)= 1是不能被证明的(即使大数学家欧拉曾给出不能令人信服的...

  • 1-2-1-1-1

    【下马请罪】 子龙下马,向张飞跪地请罪道:“张将军,一时失手……”话未停,便被张飞一矛刺了个透心凉。子龙堵着胸口汩...

  • 1 1:1 1(原创小说)

    闪回:那天她…… 当时,我确实听到了那个声音,可如今却怎么也记不清了。 掉下来了。 我觉得,那一刻...

  • 《1+1=1-1》

    十一月十一日晚,致X小姐。 十月初九, 一个人购物的孤独, 你谈起, 月光下轧过的马路, 金钱带不来满足, 忙忙碌...

  • 1+1=-1

    结婚育子这几年,在磕磕碰碰中一路走来,才恍然大悟,自己真正的成长,始于育儿。 婚前是父母的公主,虽说家境贫困,却得...

网友评论

      本文标题:100DaysLeetcode(1)

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