1 #include <iostream> 2 using namespace std; 3 // o(nlogn),判斷每一個數中有多少個1 4 int numOfOnes1(int n) 5 { 6 int i, j, count; 7 count = 0; 8 for (i = 1; i <= n; i++) 9 { 10 j = i; 11 while (j) 12 { 13 if (j % 10 == 1) 14 count++; 15 j /= 10; 16 } 17 } 18 return count; 19 } 20 /* 21 經過不斷例子,咱們發現了必定的規律 22 不失通常性, 對於5位數而言,N = abcde 23 咱們能夠分別求各個位數上"1"的個數,下面咱們先求百位上"1"的個數 24 若c > 1, 百位上"1"的個數爲100 * (高位數字 +1) 25 若c = 1, 百位上"1"的個數爲100 * 高位數字 + (低位數字 + 1) 26 若c = 0, 百位上"1"的個數爲100 * 高位數字 27 簡單分析就能夠知道爲o(len)的時間複雜度,快了不少倍啊 28 */ 29 int numOfOnes2(int n) 30 { 31 int i, count, high, low, cur; 32 i = 1; 33 count = 0; 34 while (n >= i) 35 { 36 high = n / (i * 10); 37 cur = (n / i) % 10; 38 low = n % i; 39 if (cur == 0) 40 count += high * i; 41 else if (cur == 1) 42 count += high * i + low + 1; 43 else 44 count += (high + 1) * i; 45 i *= 10; 46 } 47 return count; 48 } 49 int main() 50 { 51 int n; 52 n = 120; 53 //test 54 cout<<numOfOnes1(n)<<endl; 55 cout<<numOfOnes2(n)<<endl; 56 system("pause"); 57 return 0; 58 }