我当时在练习算法问题,这是在HackerRank网站上进行的,我首先用C语言提交了我的代码,但是我得到了一些错误的测试用例。我认为我的逻辑是正确的,所以我将代码移植到Java,并通过了所有测试用例。
链接到问题定义: https : //www.hackerrank.com/challenges/caesar-cipher-1
这是我在C中的代码:
int main(){
int n;
scanf("%d", &n);
char* s = (char *)malloc(n * sizeof(char));
scanf("%s", s);
int k;
scanf("%d", &k);
k = k % 26;
for(int i = 0; i < n; i++){
if(s[i] >= 65 && s[i] <= 90){
s[i] += k;
if(s[i] > 90){
s[i] = s[i] - 90 + 64;
}
}
if(s[i] >= 97 && s[i] <= 122){
s[i] += k;
if(s[i] > 122){
s[i] = s[i] - 122 + 96;
}
}
}
printf("%s", s);
return 0;
}
这是我的Java代码:
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
String str = br.readLine();
int K = Integer.parseInt(br.readLine());
K %= 26;
for(int i = 0; i < N; i++){
char c = str.charAt(i);
if(c >= 65 && c <= 90){
c += K;
if(c > 90){
c = (char)(c - 90 + 64);
}
}
if(c >= 97 && c <= 122){
c += K;
if(c > 122){
c = (char)(c - 122 + 96);
}
}
System.out.print(c);
}
}
}
我的两个解决方案都通过了样本测试用例,逻辑都一样。我不明白为什么在某些测试用例中它会在C中显示W / A。
PS:这是练习题解决方案,而不是现场比赛解决方案。
C字符串以'\0'
附加在其末尾的特殊字符结尾。因此,实际字符串的字符总是1
比可见文本长。您没有为输入字符串null终止符分配内存:替换
char* s = (char *)malloc(n * sizeof(char));
和
char* s = malloc(n * sizeof(char) + 1);
甚至
char* s = malloc(n + 1);
如sizeof(char)
所保证的那样1
。
另外,这些行会出现问题:
if(s[i] >= 97 && s[i] <= 122){
s[i] += k;
s[i]
可能122
并且k
可能会比5
。作为s[i]
最有可能签约char
的类型,而且可能溢出过去的价值127
,这是最大的签署char
。有符号整数溢出具有未定义的行为。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句