233. Number of Digit One

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)  +(m-1) * 6 * pow(10,m-2) + func(41)

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

func(141) = 41+1 +(m-1)*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);
    }
};

 

转载于:https://www.cnblogs.com/zengzy/p/5059099.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值