我编写了一个Caesar密码,它似乎在大多数测试中有效,但在少数情况下失败了。有关测试详情的更多信息,请https://www.hackerrank.com/challenges/caesar-cipher-1
基本信息:密码只加密字母,符号等保持未加密状态。
在这种情况下失败:
90
!m-rB`-oN!.W`cLAcVbN/CqSoolII!SImji.!w/`Xu`uZa1TWPRq`uRBtok`xPT`lL-zPTc.BSRIhu..-!.!tcl!-U
62
其中90是n(字符串中的字符),第二行是数组s中的字符串,62是k(字母旋转量)
对我的代码缺陷的任何见解都将受到高度赞赏
代码:
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;
}
答案 0 :(得分:0)
Old Code:
if((s[i] + k) >= 'Z' )
New Code:
if((s[i] + k) > 'Z' )
当给出P(ascii 80)时,它应该已经停止了,它应该在Z(ascii 90)处停止,而是进行了这个计算:
s[i] - 26 + k = 64
80 - 26 + 10 = 64 (ascii for @) and thus '@' was returned instead of Z