Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

Lesson learnt: one effective solution for bit\digit counting problems: counting by digit\bit

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;
    }
};
posted on 2015-11-04 07:31  Tonix  阅读(214)  评论(0编辑  收藏  举报