프로그래머스 #JS - 시저암호

SSO·2020년 1월 8일
0

프로그래머스Lv1

목록 보기
19/47
post-custom-banner

문제

https://programmers.co.kr/learn/courses/30/lessons/12926

풀이

  1. 2020
function solution(s, n) {
    var answerArr = [];
    var answer = '';
    var upperS =["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
    var lowerS = upperS.map(str=>str.toLowerCase());
    var lengthS = s.length;
  
  for(var i=0; i<lengthS; i++){
    if(s[i]===" "){
        answerArr[i] = " ";
    } else if(s[i]===s[i].toLowerCase()){
      for(var j=0; j<26; j++){
        if(s[i] === lowerS[j]){
          answerArr[i] = lowerS[((j+n)%26)];
        }
      }
    }else if(s[i]===s[i].toUpperCase()){
      for(var j=0; j<26; j++){
        if(s[i] === upperS[j]){
          answerArr[i] = upperS[((j+n)%26)];
        }
      }
    }
  }
  answer = answerArr.join('');
    return answer;
}

더 생각해보기

  string 관련 method를 이용해서 코드를 간략화 해볼 것
2. 2019

function solution(string, num) {
    var answer = '';
    var upperCase = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
    var lowerCase = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];
    var lengthOfString = string.length;

    for(var i = 0; i < lengthOfString; i++){
        var one = string[i];
        
        if (one === ' ') {
          answer = answer + ' ';
          continue;
      } 
      
      var index = upperCase.indexOf(one);
      
      if (index === -1) {
        index = lowerCase.indexOf(one);
         if ((index + num) <= 25 ){
           answer =  answer + lowerCase[index + num];
       } else {
           answer = answer + lowerCase[index + num - 26];
       } 
        continue;
      }
     
      if ((index + num) <= 25 ){
           answer =  answer + upperCase[index + num];
       } else {
           answer = answer + upperCase[index + num - 26];
       } 
    }
    
    return answer;
}

참고사항

String 관련 method - charCodeAt(), fromCharCode(), replace()
upperCase인지 lowerCase인지 확인하는 법

profile
happy
post-custom-banner

0개의 댓글