[#20][알고리즘] 시저 암호(Caesar cipher)

프로그래머스 > 시저 암호(Caesar cipher)

문제 링크(https://programmers.co.kr/learn/challenge_codes/144)














C++풀이
#include<iostream>
#include<string>
using namespace std;
string caesar(string s, int n)
{
  while(n>26){
    n -= 26;
  }
  int size = s.length();
  char c[size];
  string answer = "";
  for(int i = 0 ; i < s.length(); i++){
    //각 자리 n만큼 밀기 
    if(s.at(i)!=32){
      if(s.at(i) >= 97 && s.at(i)+> 122){
        //소문자 처리
        s.at(i) -= 26;
        c[i]= s.at(i)+n;
      } else if(s.at(i)+> 90 && s.at(i) > 64 && s.at(i) <= 90){
        //대문자 처리
        s.at(i) -= 26;
        c[i]= s.at(i)+n;
      } else{
          c[i] = s.at(i) + n;
      }
    } else{
      //공백 처리
      c[i] = 32;
    }
  }
  answer = c;
  return answer.substr(0,size);
}
int main()
{
    string text = "aB Ba zZ";
    int testNo = 25;
    string testAnswer = caesar(text, testNo);
    cout<<testAnswer;
}
cs
1. n의 범위 조절.
 n이 4일 때, 30일 때 모두 같은 결과가 나오기 때문
2. 공백과 공백이 아닌 문자 구분
3. 공백일 경우 공백으로 유지
4. 공백이 아닐 경우 대문자/소문자 구분
5. 소문자의 경우 n만큼 밀었을 때 z(122)를 넘어가면
 : 26만큼 뺀 후 n을 더한다
6. 대문자의 경우 n만큼 밀었을 때 Z(90)를 넘어가면
 : 26만큼 뺀 후 n을 더한다.


댓글

가장 많이 본 글