[백준 5598] 카이사르 암호 (C#, C++) - soo:bak
작성일 :
문제 링크
설명
카이사르 암호 방식을 사용하여 암호화된 문자열을 복호화하는 문제입니다.
- 입력은 모두 대문자로 이루어진 알파벳 문자열입니다.
- 카이사르 암호 방식은 원래의 알파벳에서 세 칸 뒤의 문자를 암호문으로 사용했다고 설명되어 있습니다.
- 예를 들어,
'D'
→'A'
,'E'
→'B'
와 같은 방식입니다. - 알파벳은 순환되며,
'A'
에서1
만큼 앞으로 이동하면'Z'
가 됩니다.
접근법
- 입력된 문자열을 한 글자씩 순회합니다.
- 각 문자를
-3
이동시키되,'A'
보다 작아지면 알파벳 순환을 고려해+26
을 더해줍니다. - 최종 복호화된 문자열을 출력합니다.
Code
[ C# ]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
using System;
class Program {
static void Main() {
string input = Console.ReadLine();
char[] decrypted = new char[input.Length];
for (int i = 0; i < input.Length; i++) {
decrypted[i] = (char)(input[i] - 3);
if (decrypted[i] < 'A')
decrypted[i] = (char)(decrypted[i] + 26);
}
Console.WriteLine(new string(decrypted));
}
}
[ C++ ]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
string str; cin >> str;
for (size_t i = 0; i < str.size(); i++) {
str[i] -= 3;
if (str[i] < 'A') str[i] += 26;
}
cout << str << "\n";
return 0;
}