hackerrank问题:给定一个字符串,由字母和数字组成,在给定的字符串中找到每个数字的频率
;这里错了吗?我的CodeBlocks给出了正确的输出,但在Hackerrank中,它的答案错误。
#include <string.h>`
#include <math.h>
#include <stdlib.h>
int main() {
char s[1000];
char a[10]={0,0,0,0,0,0,0,0,0,0};
int i;
scanf("%[^\n]", s);
int l = strlen(s);
for(i=0; i<l; i++){
int m = s[i]-48;
a[m]=a[m]+1;
}
for(i=0; i<9; i++){
printf("%d ", a[i]);
}
printf("%d", a[9]);
return 0;
}```
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果将条件放置为M&gt; = 0和M&lt; 10,则a [m] ++。该代码可以正常工作。
工作代码。也更新为1001。
If you put the condition m>=0 and m<10 then a[m]++. The code will work fine.
Working code. Also updated size to 1001.
对于初学者,这些标头
是多余的。可以在不使用标头声明的情况下编写该程序。
相反,您需要包括标题
&lt; stdio.h&gt;
数组
a
应该具有类型size_t
。即使对于具有1000
元素的字符数组,char> char
的对象也无法存储如此大的值。数组的初始化
a
也可以更简单,因为从作业中遵循字符数组
s
应该能够存储一个等于>>>>>的长度的字符串。 1000
。这意味着字符数组本身至少应具有1001
字符,以便能够存储带有1000 <的字符串的终止零字符
'\ 0'
/代码>字符。这些语句
可能会导致访问数组调用未定义行为的数组之外的内存,因为没有检查当前字符是否包含数字。
该程序可以以以下方式查看。
例如,如果要输入字符串
“
12233344444555555555666666666666666777777777777777777777777777777777777777777777777777777777777777799999999999999
”
For starters these headers
are redundant. The program can be written without using any declaration from the headers.
Instead you need to include the header
<stdio.h>
The array
a
should have the typesize_t
. Even for the character array having1000
elements an object of the typechar
can be unable to store such big values.And the initialization of the array
a
can be simplerAlso as it follows from the assignment the character array
s
should be able to store a string with the length equal to1000
. It means that the character array itself shall have at least1001
character to be able to store also the terminating zero character'\0'
of a string with1000
characters.These statements
can result in accessing memory beyond the array
a
that invokes undefined behavior because there is no check whether the current character contains a digit.The program can look the following way.
For example if to enter string
"122333444455555666666777777788888888999999999"
then the output will look likeIf you need to output frequencies in one line then instead of this statement
just write
In this case for the above string the output will be