[LeetCode 解题报告]233. Number of Digit One

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

Example:

Input: 13
Output: 6 
Explanation: Digit 1 occurred in the following numbers: 1, 10, 11, 12, 13.
class Solution {
public:
    int countDigitOne(int n) {
        vector<int> res(10, 0);
        int value = 1;
        countDigit(n, res, value);
        return res[1];
    }
    
    void countDigit(int n, vector<int>& res, int& value) {
        if (n <= 0)
            return ;
        int one = n%10;
        n /= 10;
        int ten = n;
        
        for (int i = 0; i <= one; i ++)
            res[i] += value;
        
        while (ten) {
            res[ten%10] += (one+1)*value;
            ten /= 10;
        }
        
        for (int i = 0; i < 10; i ++)
            res[i] += value*n;
        res[0] -= value; // 将第一位是0的排除
        value *= 10;
        countDigit(n-1, res, value);
    }
};
发布了467 篇原创文章 · 获赞 40 · 访问量 45万+

猜你喜欢

转载自blog.csdn.net/caicaiatnbu/article/details/104215226
今日推荐