找出0,1,2,3,...,n中,包含的数字2的个数。
比如,0,1,2,3,4,...,12包含的2的个数是2(2和12分别包含一个2).又如,0,1,2,...,25,包含8个2.
可以用递归的方法做这个题,代码如下,易读性还是很好的,就不多解释了。
#include "stdio.h"
#include "stdlib.h"
int count2sR(int n)
{
if(n==0) return 0;
// 513 = 5*100+13. [power=100, first = 5, remainder=13]
int power = 1;
while(10*power<n) power*=10;
int first = n/power;
int remainder = n%power;
// Count 2s from first digit
int nTwoFirst = 0;
if(first>2) nTwoFirst+=power;
else if(first==2) nTwoFirst+=remainder+1;
// Count 2s from all other digits
int nTwoOther = first* count2sR(power-1) + count2sR(remainder);
return nTwoFirst+nTwoOther;
}
int main()
{
printf("%d\n",count2sR(1414));
}