Leetcode P0233"Number of Digit One" 题解

2020/11/10 Leetcode

博文中会简要介绍Leetcode P0233题目分析及解题思路。

“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.

以下是C++的题解代码实现。

class Solution {
public:
    int countDigitOne(int n) {
        int counter = 0;
        for (long long i = 1; i <= n; i *= 10) {
            long long divider = i * 10;
            counter += (n / divider) * i + min(max(n % divider - i + 1, 0LL), i);
        }
        return counter;
    }
};

Search

    Table of Contents