美文网首页
两数相加

两数相加

作者: 自律_自强_通达 | 来源:发表于2020-12-02 22:46 被阅读0次

    /// "两数相加"

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

    相关文章

      网友评论

          本文标题:两数相加

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