Swift Solution


  • 0
    S
    func myAtoi(_ str: String) -> Int {
        
        guard str.characters.count > 0 else {
            return 0
        }
        var chars = str.trimmingCharacters(in: .whitespaces).characters
        
        var isNegative = false
        
        if chars.first == Character("+") || chars.first == Character("-") {
            if chars.first == Character("-") {
                isNegative = true
            }
            chars.removeFirst()
        }
    
        var totalNumber: Double = 0
        
        while let char = chars.first, let number = Double(String(char)) {
           totalNumber *= 10
    
            chars.removeFirst()
    
            totalNumber += number
        }
        
        if totalNumber > Double(Int32.max) || totalNumber < Double(Int32.min) {
            return isNegative ? Int(Int32.min) : Int(Int32.max)
        } else {
            let num = Int(totalNumber)
            return isNegative ? num * -1 : num
        }
        
    }
    

Log in to reply
 

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