比较快的计算1~N中出现数字K的次数

/*O(lg(N)*/
#include"iostream"
using namespace std;
long Countk2(long n,long k)

{
    long count = 0;
    long i = 1;
    long current = 0,after = 0,before = 0;
    while((n / i) != 0)
    {          
        current = (n / i) % 10;
        before = n / (i * 10);
        after = n - (n / i) * i;
        if (current > k)
            count = count + (before + 1) * i;
        else if (current <k)
            count = count + before * i;
        else if(current ==k)
            count = count + before * i + after + 1;
       i = i * 10;
   }
    return count;
}
int main()
{
	long n,k;
	while(cin>>n>>k)
	{
		cout<<Countk2(n,k)<<endl;
	}
	return 0;
}
posted @ 2011-05-20 20:57  Ac_smile  阅读(482)  评论(0)    收藏  举报