LeetCode 233: Number of Digit One

Problem Description

Explanation

To solve this problem, we can iterate through each digit of the numbers from 1 to n and count the occurrence of digit 1 in each position (ones place, tens place, etc.). We can then sum up these counts to get the total number of digit 1's in all numbers from 1 to n.

The algorithm involves analyzing the current digit being considered, the higher digits, and the lower digits. By considering each digit individually and calculating the contribution of that digit to the total count of digit 1's, we can determine the final result.

Time Complexity

The time complexity of this algorithm is O(logn) because we are iterating through the digits of the number n.

Space Complexity

The space complexity of this algorithm is O(1) as we are using a constant amount of extra space.

Solutions

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

Loading editor...