Decode
Time limit: 2000 ms
Memory limit: 65536 KB
Description
Julius Caesar used a system of cryptography, now known as Caesar Cipher, which shifted each letter 2 places further through the alphabet (e.g. ‘A’ shifts to ‘C’, ‘R’ shifts to ‘T’, etc.). At the end of the alphabet we wrap around, that is ‘Y’ shifts to ‘A’.
We can, of course, try shifting by any number. Given an encoded text and a number of places to shift, decode it.
For example, “TOPCODER” shifted by 2 places will be encoded as “VQREQFGT”. In other words, if given (quotes for clarity) “VQREQFGT” and 2 as input, you will return “TOPCODER”. See example 1 below.
Input Format
First line will be the cipher text String, between 0 to 50 characters (inclusive) long. Each character is an uppercase letter ‘A’ – ‘Z’.
Second line will be an integer shift (0 <= shift <= 25), which is the number of places to shift.
Output Format
The decoded String.
Sample Input 1
VQREQFGT 2
Sample Output 1
TOPCODER
Sample Input 2
ABCDEFGHIJKLMNOPQRSTUVWXYZ 10
Sample Output 2
QRSTUVWXYZABCDEFGHIJKLMNOP
Sample Input 3
TOPCODER 0
Sample Output 3
TOPCODER
Sample Input 4
ZWBGLZ 25
Sample Output 4
AXCHMA
Sample Input 5
DBNPCBQ 1
Sample Output 5
CAMOBAP
Sample Input 6
LIPPSASVPH 4
Sample Output 6
HELLOWORLD
Solution
#include <stdio.h> #include <stdlib.h> int main() { char str[50], alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; char * pch; int shift = 0, i, tempIndex; unsigned int size; fflush(stdin); scanf("%s",&str); scanf("%d",&shift); if(shift>=0 && shift <= 25){ size = strlen(str); char result[size]; // printf("%d %d",(pch-alphabet), strlen(str)); for(i = 0 ; i < size; i++){ pch =strchr(alphabet,str[i]); tempIndex = pch-alphabet; tempIndex = tempIndex - shift; if(tempIndex < 0){ tempIndex = (unsigned)strlen(alphabet) + tempIndex; } result[i] =alphabet[tempIndex]; printf("%c",result[i]); } printf("\n"); } return 0; }