程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> 從1到n之間的數字1出現的次數

從1到n之間的數字1出現的次數

編輯:C++入門知識

例如N=11時結果為4(只有1,10,11含1) 1.常規方法(暴力)時間復雜度O(n*logn)當n很大的時候,效率低。 [cpp]   #include <iostream>   #include <cstdio>   using namespace std;      int function (int n)   {       int count=0;       for (int i=1 ;i<=n;i++)       {           int j = i;           while (j)           {               if (j%10==1)                   count++;               j/=10;           }       }       return count;   }   int main ()   {       int n;       while (scanf ("%d",&n)!=EOF)       {           printf ("%d\n", function(n));       }       return 0;   }     2.編程之美上解法(時間復雜度O(logn)) [cpp]   #include <iostream>   #include <cstdio>   using namespace std;      int function (int n)//按照每一位出現1的次數來進行計算   {       int factor =1 ;//factor 是該位的權值       int res = 0;       int low, cur, high;       while (n / factor)       {           low = n % factor;//數字的低位           cur = n / factor % 10;//數字當前位置的數           high = n / factor / 10;//數字的最高位           if (cur==0)               res += high * factor;           else if(cur==1)               res += high * factor + low + 1;           else                res += (high + 1) * factor;           factor *= 10;       }  www.2cto.com     return res;   }   int main()   {       int n;       while (scanf("%d",&n)!=EOF)       {           printf("%d\n",function(n));       }       return 0;   }    

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved