#include "stdio.h"
#include "string.h"
#define maxn 10000000 + 10
int main()
{
char s[maxn];
scanf("%s",s);
int tot = 0;
for (int i = 0;i<strlen(s);i++)
{
if (s[i] == '1')
tot++;
}
printf("%d\n",tot);
}
书上的思考题,说是这段代码一个地方导致效率低下,请指出是哪里,我实在看不出哪里可以再快了。
当你输入的字符串较小时,可能也没啥区别,但当输入的字符串较大时,for循环里的 i<strlen(s)中的strlen(s)要执行很多次,导致效率低。
strlen(s), 每次循环都要计算这个值;可以定义一个变量 int len = strlen( s );
用一个变量代替strlen(s),
int length =strlen(s);
for(int =0;i<length;i++)
这样写,上面那种方法,每一次循环都会执行和调用一次strlen函数,导致不必要的运算,你加上计时函数,运行比较一下看时间,就知道了