gpt4 book ai didi

凯撒密码缺陷

转载 作者:行者123 更新时间:2023-11-30 16:51:00 24 4
gpt4 key购买 nike

我编写了一个凯撒密码,它似乎在大多数测试中都有效,但在少数情况下失败了。有关测试详细信息的更多信息为 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;
}

最佳答案

好的,伙计们,我已经弄清楚了。

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

关于凯撒密码缺陷,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41935063/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com