시저 암호

강동휘·2022년 12월 7일
0

프로그래머스

목록 보기
5/6
post-thumbnail


//알파벳 선언
const alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";


function solution(s, n) {
   let answer = '';
   
    for(let i =0; i< s.length; i++){
        if(s[i] === ' '){
            answer += s[i]
        }else{
            let idx=alphabet.indexOf(s[i])
            const word = idx > 25 ? 
                  alphabet.slice(26, alphabet.length)
                  :  alphabet.slice(0, 25 + 1)
            idx = word.indexOf(s[i]) + n
            if(idx >= 26){
                idx -= 26    
            }
           answer += word[idx]
            }
        }   
    return answer
}


const lower = 'abcdefghijklmnopqrstuvwxyz'; // 소문자 알파벳만 저장
const upper = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; // 대문자 알파벳만 저장


function solution(s, n) {
   const answer = s.split('')
                   .reduce((acc, cur)=>{
                   const word = lower.includes(cur) ? lower : upper
                   let idx = word.indexOf(cur) + n
                   
                    if(idx >= 26){
                        idx -= 26
                    }
                       return acc + (acc === ' ' ? ' ' : word[idx])
                   }, '')
   return answer
}
profile
👨🏻‍💻프론트엔드에서 pm으로 커리어 전향을 희망하는

0개의 댓글