I have coded a Caesar cipher that seem to work in most tests but fails on a few cases. More on the test details are https://www.hackerrank.com/challenges/caesar-cipher-1
Basic info: The cipher only encrypts letters, symbols etc stay unencrypted.
Fails on this case:
90
!m-rB`-oN!.W`cLAcVbN/CqSoolII!SImji.!w/`Xu`uZa1TWPRq`uRBtok`xPT`lL-zPTc.BSRIhu..-!.!tcl!-U
62
Where 90 is n (characters in string), second line is string in array s, and 62 is k (amount of letter rotations)
Any insight into the flaw of my code will be highly appreciated
Code:
int main(){
int n;
scanf("%d",&n);
char* s = (char *)malloc(10240 * sizeof(char));
scanf("%s",s);
int k;
scanf("%d",&k);
if (k>26) {
k%=26;
}
int rotation;
for(int i = 0; i<n; i++) {
if (s[i] >= 'a' && s[i] <= 'z') {
if((s[i] + k) > 'z' ) {
rotation = (s[i] - 26) + k;
s[i] = rotation;
} else {
s[i] = s[i]+k;
}
} else if (s[i] >= 'A' && s[i] <= 'Z') {
if((s[i] + k) >= 'Z' ) {
rotation = (s[i] - 26) + k;
s[i] = rotation;
} else {
s[i] = s[i]+k;
}
}
}
for(int i=0; i<n; i++) {
printf("%c", s[i]);
}
return 0;
}
Ok guys, so I've figured it out.
Old Code:
if((s[i] + k) >= 'Z' )
New Code:
if((s[i] + k) > 'Z' )
It messed up when given a P(ascii 80), it should have stopped at Z(ascii 90) but instead did this calculation:
s[i] - 26 + k = 64
80 - 26 + 10 = 64 (ascii for @) and thus '@' was returned instead of Z