본문 바로가기
python-algorithm

Hacker rank Caesar Cipher

by 무적김두칠 2022. 11. 10.

https://www.hackerrank.com/challenges/caesar-cipher-1

 

Caesar Cipher | HackerRank

Encrypt a string by rotating the alphabets by a fixed value in the string.

www.hackerrank.com

 

1
2
3
4
5
6
7
8
9
10
11
12
def caesarCipher(s, k):
    # Write your code here
    answer = ''
    k = k% 26
    for i in s:
        if i.isalpha():
            if ord(i)+k>122 or (ord(i)<=90 and ord(i)+k>90) :
                i = chr(ord(i) + k-26)
            else:
                i = chr(ord(i) + k)
        answer+=i
    return(answer)
cs

k가 26이 넘어가면 한바퀴를 더 도는거니까 26(알파벳 총 개수)로 나눠줌 : = k% 26
IF K is over 26, it means round over alphabets, So We should divide 26(Alphabets)
문자가 대문자거나 소문자인데 더해서 아스키코드상에 대문자로 나올수도 있으므로 예외처리
Case when the letter is Large or is small but added letter in ascii can be Large should be handled
if ord(i)+k>122 or (ord(i)<=90 and ord(i)+k>90) :

반응형

댓글