[프로그래머스]시저 암호(Swift)

brick·2023년 1월 27일
0

코테

목록 보기
15/53
func solution(_ s:String, _ n:Int) -> String {
    var asciis = Array(s).map { Int($0.asciiValue!) }

    return asciis.map { 
        var ascii = $0

        switch ascii {
            case 65...90:
                ascii = (ascii + n - 65) % 26 + 65 
            case 97...122:
                ascii = (ascii + n - 97) % 26 + 97 
            default:
                break
        }
        return String(UnicodeScalar(ascii)!)
    }.joined()
}

func solution(_ s:String, _ n:Int) -> String {
    let alphabets = "abcdefghijklmnopqrstuvwxyz".map { $0 }
    return String(s.map {
        guard let index = alphabets.firstIndex(of: Character($0.lowercased())) else { return $0 }
        let letter = alphabets[(index + n) % alphabets.count]
        return $0.isUppercase ? Character(letter.uppercased()) : letter
    })
}

0개의 댓글