작성일 :

문제 링크

11655번 - ROT13

설명

ROT13 방식으로 문자열을 암호화하는 간단한 구현 문제입니다.

  • ROT13은 알파벳 문자를 13글자 뒤로 밀어 변환하는 암호화 방식의 일종입니다.
  • 'A'~'Z' 또는 'a'~'z' 범위의 알파벳은 13글자 뒤로 밀리며, 범위를 넘어갈 경우 원형으로 이어집니다.
  • 알파벳이 아닌 문자(숫자, 공백 등)는 변환하지 않고 그대로 출력합니다.

접근법

  • 문자열을 끝까지 순회하며 알파벳 여부를 검사합니다.
  • 알파벳인 경우 'A'~'M', 'a'~'m'이면 +13, 그렇지 않으면 -13을 적용합니다.
  • 변환된 문자열을 그대로 출력합니다.

Code

[ C# ]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
using System;

class Program {
  static void Main() {
    string input = Console.ReadLine();
    char[] chars = input.ToCharArray();

    for (int i = 0; i < chars.Length; i++) {
      char c = chars[i];
      if (char.IsLetter(c)) {
        if ((c >= 'A' && c <= 'M') || (c >= 'a' && c <= 'm'))
          chars[i] = (char)(c + 13);
        else
          chars[i] = (char)(c - 13);
      }
    }

    Console.WriteLine(new string(chars));
  }
}



[ C++ ]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <bits/stdc++.h>

using namespace std;

int main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);

  string str; getline(cin, str);
  for (size_t i = 0; i < str.size(); i++) {
    if (isalpha(str[i])) {
      if ((str[i] >= 'A' && str[i] <= 'M') ||
          (str[i] >= 'a' && str[i] <= 'm')) {
        str[i] += 13;
      } else str[i] -=13;
    }
  }

  cout << str << "\n";

  return 0;
}