[HackerRank]CaesarCipher

jh Seo·2024년 2월 4일
0

HackerRank

목록 보기
10/15

개요

[HackerRank]CaesarCipher

Julius Caesar protected his confidential information by encrypting it using a cipher. Caesar's cipher shifts each letter by a number of letters. If the shift takes you past the end of the alphabet, just rotate back to the front of the alphabet. In the case of a rotation by 3, w, x, y and z would map to z, a, b and c.

접근 방식

각 string의 char원소를 'A'와 'a'간의 간격을 이용해서 푸는 방식으로 접근했다.
간격이 25가 넘으면 다른 원소로 취급한 후 string형 변수에 해당 원소를 그대로 넣고,
간격이 25가 안넘으면 알파벳에 해당하므로 k만큼 더해준 후 넣어줬다.

하지만 일부케이스에서 틀렸습니다가 나와 계속 고민하다가 결국 반례를 찾아봤다.
난 k값을 26밑으로 상정하고 풀어서 틀린 것이였다.

k값이 87이 들어오면 k-26해도 25이하의 수가 안 나온다!
따라서 k를 26으로 나머지 연산을 취한 후 제출했더니 맞았습니다가 떴다.

전체 코드

/*
 * Complete the 'caesarCipher' function below.
 *
 * The function is expected to return a STRING.
 * The function accepts following parameters:
 *  1. STRING s
 *  2. INTEGER k
 */

string caesarCipher(string s, int k) {
    string ret="";
    k%=26;
    for(char elem : s){
        if(elem-'A'<=25 && elem-'A'>=0){
            if(elem-'A'+k>25){
                ret += 'A'+(elem-'A'+k-26);
            }
            else
                ret += 'A'+(elem-'A'+k);
        }
        else if(elem-'a'<=25 && elem-'a'>=0){
            if(elem-'a'+k>25){
                ret+= 'a'+(elem-'a'+k-26);
            }
            else
                ret +='a'+ (elem - 'a'+k);
        }
        else
            ret+=elem;
    }
    return ret;
}

생각

범위 좀 잘 봐야겠다.

profile
코딩 창고!

0개의 댓글