My accepted swift solution - How can I reduced runtime?


  • 0
    U

    class Solution {
    func addTwoNumbers(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {

        var carry : Int = 0
        var head : ListNode?
        var firstNode : ListNode?
        
        var l1 = l1
        var l2 = l2
        
        while l1 != nil || l2 != nil || carry > 0 {
            
            let tempNode = ListNode(0)
            
            var sum = 0
            
            if let l1Object = l1
            {
                sum = sum + l1Object.val
            }
            
            if let l2Object = l2
            {
                sum = sum + l2Object.val
            }
            
            
            sum = sum + carry
            
            
            carry = sum / 10
            tempNode.val = sum % 10
            
            if let headNode = head
            {
                headNode.next = tempNode
                head = headNode.next
            }else
            {
                head = tempNode
                firstNode = head
            }
            
            l1 = validateIfNodeHasNext(nodeObj: l1)
            l2 = validateIfNodeHasNext(nodeObj: l2)
                
        }
        
        return firstNode
    
    }
    
    func validateIfNodeHasNext(nodeObj : ListNode?) -> ListNode? {
        
        if let obj = nodeObj {
            
            if let nextObj = obj.next
            {
                return nextObj
                
            }
        }
    
        return nil
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.