-
Notifications
You must be signed in to change notification settings - Fork 0
/
shift.cpp
60 lines (45 loc) · 1.26 KB
/
shift.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <iostream>
#include <string>
using namespace std;
string encrypt(string message, int shift)
{
string result = "";
// Iterate through each character in the message
for (int i = 0; i < message.length(); i++)
{
// Shift the character by the given amount
char c = message[i] + shift;
// Wrap around if the shifted character goes beyond 'z'
if (c > 'z')
c = 'a' + (c - 'z' - 1);
result += c;
}
return result;
}
string decrypt(string message, int shift)
{
string result = "";
// Iterate through each character in the message
for (int i = 0; i < message.length(); i++)
{
// Shift the character by the given amount
char c = message[i] - shift;
// Wrap around if the shifted character goes beyond 'a'
if (c < 'a')
c = 'z' - ('a' - c - 1);
result += c;
}
return result;
}
int main()
{
string message = "hello world";
int shift = 3;
// Encrypt the message
string encrypted = encrypt(message, shift);
cout << "Encrypted message: " << encrypted << endl;
// Decrypt the message
string decrypted = decrypt(encrypted, shift);
cout << "Decrypted message: " << decrypted << endl;
return 0;
}