Lesson learnt: one effective solution for bitdigit counting problems: counting by digitit
http://www.hawstein.com/posts/20.4.html
class Solution { public: /* * param k : As description. * param n : As description. * return: How many k's between 0 and n. */ int digitCounts(int k, int n) { int ret = 0; int base = 1; while (n/base > 0) { int cur = (n/base) % 10; int low = n - (n/base) *base; int high= n / (base * 10); ret += high * base; // at least this many if (cur == k) { ret += low + 1; // all k-xxxxx } else if(cur > k) { if(!(!k && base > 1)) // in case of 0 ret += base; // one more base } base *= 10; } return ret; } };