알고리즘 문제 풀기

<leetCode> 8. String to Integer (atoi)

studying develop 2021. 1. 15. 00:27

음 뻘짓을 너무 많이했는데, 그냥 문제가 안내하는 단계로만 하면 풀리는데, 혼자 그냥 만들해봄... 

내가 만들면 왜케 이상하지

 

class Solution {
    let max = 1 << 31 - 1
    let min = -1 * (1 << 31)
    
    let maxAbsolute: Double = Double((1 << 31) - 1)
    let minAbsolute: Double = Double((1 << 31))
    
    enum Pos {
        case pos
        case neg
    }
    
    func myAtoi(_ s: String) -> Int {
        var plma: Pos = .pos 
        var str: String = ""
        //1
        if let ind = s.firstIndex(where:{$0 != " "}) { 
            str = String(s[ind..<s.endIndex])
        } else {
            str = s
        }
        
        //print(str)
        
        //2
        
        let arr = Array(str)
        
        if arr.count == 0 {
            return 0
        }
        
        if arr[0] == "+" {
            plma = .pos
        } else if arr[0] == "-" {
            plma = .neg
        } else {
            plma = .pos
        }
        
        let pm = ["+", "-"]
        if arr[0] == "+" || arr[0] == "-" {
            let ind = str.index(str.startIndex, offsetBy: 1)
            str = String(str[ind..<str.endIndex])
        }
        
        //print(plma)
        
        //3
        
        let digits = ["0","1","2","3","4","5","6","7","8","9"]
        
        if let ind2 = str.firstIndex(where: {
            digits.contains(String($0)) == false
        }) {
            str = String(str[str.startIndex..<ind2])
        }
        
        print(str)
        
        //4
        
        let digits3 = ["1","2","3","4","5","6","7","8","9"]
        
        if let ind3 = str.firstIndex(where: {
            digits.contains(String($0)) == false
        }) {
            str = String(str[ind3..<str.startIndex])
        }
        
        //print(str)
        
        var intVal = 0
        
        //5
        //print(Double(str))
        
        if let uint64 = Double(str) {
            if plma == .neg {
                if uint64 > minAbsolute {
                    return min
                } else {
                    intVal = Int(uint64) * -1
                }
            } else if plma == .pos {
                //print(uint64, maxAbsolute)
                if uint64 > maxAbsolute {
                    return max
                } else {
                    intVal = Int(uint64)
                }
            }
        } else {
            return 0
        }
        
        return intVal
    }
}