Julius Caesar Cipher#2164

Julius Caesar Cipher (Editorial)

To decrypt the text, each letter should be shifted positions backward in a cyclic manner. We number the letters from ('') to ('').

Let be the current letter of the cipher. Its position in the alphabet is computed as - ''. To perform the backward shift while considering the cyclic nature of the alphabet (where '' comes before ''), subtract and take the result modulo . Then, add '' to obtain the ASCII code of the decrypted letter.

Thus, the decryption operation is as follows:

s[i] = (s[i] - 'A' - k + 26)~\%~26 + 'A'

Algorithm implementation

Store the input string in the character array .

char s[1000];

Read the input data.

gets(s); scanf("%d", &k);

Transform the characters of the string according to the decryption rule.

for (i = 0; i < strlen(s); i++)
  s[i] = (((s[i] - 'A') + 26 - k) % 26) + 'A';

Print the decrypted text.

puts(s);

Algorithm implementation – STL

Read the input data.

cin >> s >> k;

Transform the characters of the string according to the decryption rule.

for (i = 0; i < s.size(); i++)
  s[i] = (((s[i] - 'A') + 26 - k) % 26) + 'A';

Print the decrypted text.

cout << s << endl;

Python implementation

Read the input data.

s = input()
k = int(input())

Transform the characters of the string according to the decryption rule.

s = ''.join(chr(((ord(c) - ord('A') - k + 26) % 26) + ord('A')) 
                for c in s)

Print the decrypted text.

print(s)