[프로그래머스/Lv1/자바스크립트] 시저 암호

2023. 5. 16. 13:30

문제

https://school.programmers.co.kr/learn/courses/30/lessons/12926?language=javascript 

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr


코드

function solution(s, n) {
    var answer = ""
    var arrS = Array.from(s);
    for (var alphabet of arrS) {
        var code = alphabet.charCodeAt();
        if (code == 32) {
            answer += alphabet;
        }
        else if (code >= 65 & code <= 90) {
            var newCode = code + n;
            if (newCode > 90) {
                answer += String.fromCharCode(newCode - 26);
            }
            else {
                answer += String.fromCharCode(newCode);
            }
        }
        else {
            var newCode = code + n;
            if (newCode > 122) {
                answer += String.fromCharCode(newCode - 26);
            }
            else {
                answer += String.fromCharCode(newCode);
            }
        }
    }
    
    return answer;
}

메모

자바스크립트의 아스키코드 변환 메소드를 사용해서 문제를 푼다.

공백의 아스키코드는 32이기 때문에 아스키코드로 변환했을 때 32인 알파벳은 아무런 수정없이 answer 문자열에 더한다.

나머지 알파벳들은 아스키코드에 n을 더한 뒤 다시 문자열로 변환해서 answer 문자열에 더한다.

이때 z의 경우 다시 a로 돌아와야하기 때문에 n을 더한 아스키코드에서 알파벳 개수인 26만큼 빼줘서 a로 돌아갈 수 있게 해준다.

BELATED ARTICLES

more