google笔试题:计算1-N(N=1234567890)中1出现的次数。

来源:互联网 发布:相同图片识别软件 编辑:程序博客网 时间:2024/05/05 03:46

     从CSDN论坛中,看到有这么一道题:

有这样一个函数f(n),对于任意正整数n,它表示从 0 到 n 之间出现“1”的个数,
比如 f(1) = 1,  f(13) = 6,请列出从 1 到 1234567890 中所有的 f(n) = n 的 n, 要求准确快速. 

  感觉很有趣,自己尝试做了下。

   用指针来计算不知道速度能不能快点?

/**********************************************/

#include <stdlib.h>
#include <stdio.h>

int main(void)
{
   long int number,i,count=0;
   char *p;
   char string[10];
   printf("PLZ input the number:/n");
   scanf("%ld",&number);
   for(i=1;i<=number;i++)
   {
 itoa(i, string, 10);
    p=&string;
    while(*p!='/0')
    {
  if(*p=='1') count++;
  p++;
    }
   }
   printf("%ld/n", count);
 
}

/*******************************************************/

输入:11  输出:4
输入:10000 输出:4001
输入:10000000 输出:7279141
输入:100000000 输出:72808170
输入:10 0000 0000 输出:(等了3分钟,没有出结果,偶的CPU 1.8G的,速度太慢了。)

原创粉丝点击