알고리즘 풀이

[JAVASCRIPT] 백준 11655번 문제 풀이

Lv1_junior_dev 2023. 4. 17. 20:17

❗ 풀이

const input = require('fs').readFileSync('dev/stdin').toString().split('');

const compareArray = [];

for (let i = 0; i < input.length; i++) {
    const currentCharCode = input[i].charCodeAt(0);

    if (currentCharCode >= 65 && currentCharCode <= 90) {
        const shiftedCode = ((currentCharCode - 65 + 13) % 26) + 65;
        compareArray.push(String.fromCharCode(shiftedCode));
    } else if (currentCharCode >= 97 && currentCharCode <= 122) {
        const shiftedCode = ((currentCharCode - 97 + 13) % 26) + 97;
        compareArray.push(String.fromCharCode(shiftedCode));
    } else {
        compareArray.push(input[i]);
    }
}

console.log(compareArray.join(''));
  1. 결과값을 저장하기 위한 빈 배열을 정의
  2. 반복문을 사용하여 문자 배열을 반복하고 charCodeAt() 메서드를 사용하여 현재 문자의 ASCII 코드를 가져옵니다.
  3. ASCII 코드가 대문자 범위(65~90)에 있으면 코드는 65를 빼고 13을 더하고 26을 나눈 나머지 값에 65를 더하여 시프트된 코드를 계산하고. String.fromCharCode() 메서드를 호출하여 ASCII 코드를 문자열로 변환 후  compareArray로 push
  4. ASCII 코드가 소문자 범위(97~122)에 있으면 코드는 97을 빼고 13을 더하고 26을 나눈 나머지 값에 97을 더하여 시프트된 코드를 계산하고 String.fromCharCode() 메서드를 호출하여 ASCII 코드를 문자열로 변환 후 compareArray로 push
  5. ASCII 코드가 문자 범위 내에 있지 않으면 코드는 원래 문자를 compareArray로 push
  6. compareArray에서 변환된 문자를 결합하고 결과 문자열을 출력

❗ 주의사항

* 첫 단어나 끝 단어에 공백이 올 수도 있으므로 trim()을 사용하면 출력 형식이 잘못되었다는 오류가 발생함 *