首页 > 其他 > 详细

LintCode "Digit Counts" !!

时间:2015-11-04 08:13:30      阅读:241      评论:0      收藏:0      [点我收藏+]

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;
    }
};

LintCode "Digit Counts" !!

原文:http://www.cnblogs.com/tonix/p/4934942.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!