Refer to previous statistical ideas: count the number of times that the nth digit appears on the nth digit, 10, and, respectively.
For example, ABCDE, when calculating the number of occurrences of D-bit 1, use d as the delimiter, ABC is before, and E is after.
Considerations: (n is the length-1 of D)
When D = 0, Count = before * 10 ^ N;
When d = 1, Count = before * 10 ^ N + after;
When D> 1, Count = (before + 1) * 10 ^ N;
For example:
19x8
Count the number of times 1 on X:
1) x = 0, that is, the number of 1908 X as 1 has ~ 181x, x 0 ~ 9, 19 is before, and 8 is after
Count = 19*10 ^ 1;
2) x = 1, that is, the number of 1918 X as 1 has ~ 181x, x 0 ~ 9; in addition, 1910 ~ 1918, then 19 is before, 8 is after
In this case, Count = 19*10 ^ 1 + (8 + 1 );
3) x> 1, for example, the number of 1928 X as 1 has ~ X, 0 ~ 9, 19 is before, and 8 is after
In this case, Count = (19 + 1) * 10 ^ 1;
In particular, when X is at the leftmost end, before is 0, and after is 0 at the rightmost end.
#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;}
1 ~ N direct 1 appears