Advertisement
HXXXXJ

8. String to Integer (atoi)

Feb 13th, 2019
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 0.76 KB | None | 0 0
  1.     func myAtoi(_ str: String) -> Int {
  2.         let arr = Array(str.trimmingCharacters(in: .whitespaces))
  3.         var isNeg = false
  4.         var res = 0
  5.         for (index, char) in arr.enumerated(){
  6.             if index == 0 && char == "-"{
  7.                 isNeg = true
  8.             }else if index == 0 && char == "+" {
  9.             }else if char <= "9" && char >= "0"{
  10.                 res = res * 10 + Int(String(char))!
  11.                
  12.                 if !isNeg && res > Int32.max {
  13.                     return Int(Int32.max)
  14.                 } else if isNeg && 0 - res < Int32.min {
  15.                     return Int(Int32.min)
  16.                 }
  17.             }else{
  18.                 break
  19.             }
  20.         }
  21.        
  22.         return isNeg ? 0 - res : res
  23.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement