由买买提看人间百态

topics

全部话题 - 话题: count0
(共0页)
j**l
发帖数: 2911
1
面试的时候,test cases是重要的考查方面
假定有一个01字符串,用计数排序实现把所有的0放在左边,所有的1放在右边。
白板程序大致是这样
void CountSort01String(char str[])
{
if (str == NULL)
return;
int count0 = 0;
int count1 = 0;
int i;
for (i = 0; str[i] != '\0'; i++)
{
if (str[i] == '0')
count0++;
else if (str[i] == '1')
count1++;
else
{
printf("Invalid input string.\n");
return;
}
}
int n = count0 + count1;
for (i = 0; i < c
c**********e
发帖数: 2007
2
来自主题: Programming版 - C++: How to read until the end of file?
I have a txt file, which are 0 and 1 separated by space.
input.txt:
1 0 1 0 0 0 0 0
0 1 1 1 1 0 1
I would like to count the number of 0's and 1's. I use
the following code. My question is how to modify the while(?)
to make it read the txt file until the end? Thanks a lot.
ifstream fin;
fin.open("input.txt");
int i=0, count0=0, count1=0;

while(i==0 || i==1)
{
fin >> i;
if(i==0) count0++;
if(i==1) count1++;
}
z*j
发帖数: 42
3
I mean input exception, hardware exception, environment exception...
basically, in c, return an error number or modify global error variable.
in c++, throw an exception or return error number.
For example: those are all exceptions:
1. 输入是空指针,也就是str == NULL
2. 输入是空串,也就是"\0"或者说str[0] == '\0'
3. 输入含有0和1以外的非法字符
4. 输入只有0,还要考虑1个,2个,还是多个0
5. 输入只有1,还要考虑1个,2个,还是多个1
6. 输入有0有1,还要考虑是0的个数多还是1的个数多还是个数相同,各种可能的排列
方式,包括原来就已经排好序的情形
7. 输入串很长,比如超过int能表示的最大整数,这时候你发现原始程序要追加对
count0, count1和n溢出的处理
8. 测有没有栈溢出或者内存泄漏
s******n
发帖数: 3946
4
好了,终于想出来了:
第一遍:count0,1,2的个数l, m, n
第二遍:根据l,m,n很容易确定每个元素最终要挪到哪个位置,把数组元素值改成最终
目的地的下标
第三遍:根据a[i]!=i的条件进行swap到最终位置
第四遍:根据l,m,n恢复数组元素值为0,1,2
o***r
发帖数: 81
5
来自主题: Programming版 - C++: How to read until the end of file?
while(fin>>i){
if( i == 0 ) count0++;
if( i == 1 ) count1++;
}
(共0页)