參考前人的統計思想:分別統計個、10、百、、、億等第N位上1出現的次數。spa
如ABCDE,在統計D位1出現的次數時,用D作分割符,ABC爲Before,E爲After。code
分狀況考慮:(n爲D的length-1)blog
當D = 0 時,count = Before * 10^n ;it
當D = 1 時,count = Before * 10^n + After;io
當D > 1 時,count = (Before + 1)*10^n; class
例如:循環
19X8統計
統計X上1的次數:di
1)X = 0 ,即1908 X爲1的數有001x~181x,x取0~9則19爲Before,8爲Afterwhile
此時count = 19 * 10^1 ;
2)X = 1 ,即1918 X爲1的數有001x~181x,x取0~9;另外,1910~1918,則19爲Before,8爲After
此時count = 19 * 10^1 + (8 + 1);
3)X > 1 ,如1928 X爲1的數有001x~191x,x取0~9則19爲Before,8爲After
此時count = (19 + 1) * 10^1 ;
特別當X在最左端時Before 爲 0,最右端時After 爲0
#include <stdio.h> int Count1(int n) { int count = 0,//1出現總次數 bitCount = 0,//某位1出現次數 base = 1,//基數 before = n,after = 0, //從最右開始,則Before = n,After = 0 bitN = 0;//第N位數 while(before)//向左移,還有數時循環 { after = n % base; before = n / (base * 10); bitN = (n / base) % 10; if(bitN > 1) { bitCount = (before + 1) * base; } else if(bitN == 0) { bitCount = (before) * base; } else { bitCount = (before) * base + (after + 1); } base *= 10; count += bitCount; } return count; } int main() { int n = 121; printf("%d\n",Count1(n)); return 0; }