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

解法一:

  func addTwoNumbers(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
        
        if l1 == nil {
            return l2
        }
        
        if l2 == nil {
            return l1
        }
        
        var headNode:ListNode?
        
        var head1:ListNode? = l1
        var head2:ListNode? = l2
        var carry:Int = 0
        
        while head1 != nil {
            
            let value:Int = (head1?.val)! + (head2?.val)! + carry
            
            let listNode:ListNode? = ListNode(value % 10)
            
            if headNode == nil {
                headNode = listNode
            } else {
                var nextNode:ListNode? = headNode
                while nextNode?.next != nil {
                    nextNode = nextNode?.next
                }
                nextNode?.next = listNode
            }
            carry = value / 10
            head1 = head1?.next
            head2 = head2?.next
        }
        
        return headNode
    }

改进版:

   func addTwoNumbers2(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
        
        let headNode = ListNode(0)
        var listNode = headNode
        
        var head1:ListNode? = l1
        var head2:ListNode? = l2
        var carry:Int = 0
        
        while head1 != nil || head2 != nil || carry != 0 {
            
            var sum:Int = carry
            
            if head1 != nil {
                sum += (head1?.val)!
                head1 = head1?.next
            }
            
            if head2 != nil {
                sum += (head2?.val)!
                head2 = head2?.next
            }
            
            carry = sum / 10
            
            listNode.next = ListNode(sum % 10)
            listNode = listNode.next!
        }
        
        return headNode.next
    }

链表定义如下:

public class ListNode {
     public var val: Int
     public var next: ListNode?
     public init(_ val: Int) {
       self.val = val
       self.next = nil
     }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,959评论 0 23
  • Introduction to HTS Flywheel Energy Storage 1. 储能方式介绍 储能技...
    iminriver阅读 1,918评论 0 0
  • 准备想你的时候 我突然忘了你说过的话 我们沿着南湖大道向西走 往北拐个弯就走到火车站 你向前奔跑 我在你身后追随 ...
    周潇洒阅读 284评论 0 1
  • 谢谢你出现在我的生命里,你让我变得更坚强,灵魂却更加柔软了。 帅帅满两个月了,长得胖嘟嘟的,可爱极了。看着他熟睡的...
    知笔行阅读 379评论 0 0