Swift Elegant Solution


  • 0
    X
    class Solution {
        func addTwoNumbers(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
            var nextNumber: Int = 0
            var sum: Int = 0
            var num1: Int? = 0
            var num2: Int? = 0
            var curNum: Int = 0
            var temList: ListNode? = nil
            var teml1: ListNode? = l1
            var teml2: ListNode? = l2
            var list: ListNode? = nil
            //Optional To Keep Cycle
            while teml1 != nil || teml2 != nil {
                num1 = teml1?.val
                num2 = teml2?.val
                if num1 == nil {
                    num1 = 0
                }
                if num2 == nil {
                    num2 = 0
                }
                sum = num1! + num2! + nextNumber
                curNum = sum % 10
                if sum >= 10 {
                    nextNumber = 1
                } else {
                    nextNumber = 0
                }
                //List
                let node: ListNode = ListNode(curNum)
                if temList == nil {
                    temList = node
                    list = temList
                } else {
                    temList?.next = node
                    temList = node
                }
                //List Forward
                teml1 = teml1?.next
                teml2 = teml2?.next
                //last number >= 10  -> [0,1]
                if nextNumber == 1 && teml1 == nil && teml2 == nil {
                    //List
                    let node: ListNode = ListNode(nextNumber)
                    if temList == nil {
                        temList = node
                        list = temList
                    } else {
                        temList?.next = node
                        temList = node
                    }
                    return list
                }
            }
            return list
        }
    }
    
    
    

Log in to reply
 

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