Number of numbers 1 (thinking / mathematics)

Title: https://leetcode-cn.com/problems/number-of-digit-one/
Code: https://leetcode-cn.com/problems/number-of-digit-one/solution/shu-zi- 1-de-ge-shu-by-leetcode /
Given an integer n, calculate the number of occurrences of the number 1 in all non-negative integers less than or equal to n.
Idea: Calculate the number of contributions of 1 in each digit of the decimal number, and the code is on the card

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


Published 152 original articles · praised 2 · visits 6450

Guess you like

Origin blog.csdn.net/weixin_43918473/article/details/104870262