233 Number of Digit One(Medium)

1.算法说明:
如3141592,在m(digitDivide)=100时,即要求计算百位上“1”的个数
其中a为31415,b为92,31415中出现了3142次“1”,因为每10个数里面出现1次“1”。而实际上,31415是3141500,所以把31415中1的个数再乘以m。如3141400~3141499中,前缀为31414的数出现了100次,所以需要乘以m(此时是100)。

2.注意溢出的问题,所以在for循环里面,使用了long long类型。

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.

Hint:

  1. Beware of overflow.

Subscribe to see which companies asked this question

class Solution {
    public:
    int countDigitOne(int n) {        

        int ans=0;
        for(long long digitDivide=1;digitDivide<=n;digitDivide*=10)
        {
            int a=n/digitDivide;
            int b=n%digitDivide;
            ans+=(a+8)/10*digitDivide+(a%10==1)*(b+1);
        }
        return ans;

    }};

发表评论

电子邮件地址不会被公开。 必填项已用*标注