码迷,mamicode.com
首页 > 其他好文 > 详细

233. Number of Digit One

时间:2015-12-19 15:01:21      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:

233. Number of Digit One

Total Accepted: 13442 Total Submissions: 59263 Difficulty: Medium

Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n.

For example:
Given n = 13,
Return 6, because digit 1 occurred in the following numbers: 1, 10, 11, 12, 13.

举例分析

641中有多少个1?

求func(641)

641分为[0,599]和[600,641]

[0,599]:

固定百位的1有1*10*10种

固定十位的1有6*1*10种

固定个位的1有6*10*1种

[600,641]只需计算0-41中1的个数也就是func(41)

所以func(641) = 1*10*10+6*1*10+6*10*1+func(41);

641是一个三位数,设m=3表示n是一个m位的数

也就是func(641) = pow(10,m-1)  +  6*pow(10,m-2) + func(41)

特殊的,当最高位等于1时有点不一样。例如141

func(141) = 41 + 1*pow(10,m-2) + func(41)

class Solution {
public:
    int countDigitOne(int n) {
        if(n<=0) return 0;
        if(n<10) return 1;
        string nstr = to_string(n);
        int m = nstr.size();
        int rest = n - (nstr[0]-0)*pow(10,m-1);
        int cnt = nstr[0]==1 ? rest+1: pow(10,m-1);
        return cnt+(nstr[0]-0)*(m-1)*pow(10,m-2) + countDigitOne(rest);
    }
};

 

233. Number of Digit One

标签:

原文地址:http://www.cnblogs.com/zengzy/p/5059099.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!