LeetCode 1067: Digit Count in Range Solution

Master LeetCode problem 1067 (Digit Count in Range), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1067. Digit Count in Range

Problem Explanation

Explanation

The problem asks to count the number of digit 'd' in the range of integers from 0 to n. We can solve this problem by iterating through each number from 0 to n and counting the occurrences of the digit 'd'. However, this approach is inefficient for large values of n.

A more efficient approach is to count the occurrences of digit 'd' at each position (ones, tens, hundreds, etc.) in the range [0, n]. We can break down the problem into smaller subproblems by considering the digit 'd' at each position separately.

To count the occurrences of digit 'd' at a specific position, we can use the following formula:

count = (n / (base * 10)) * base + min(max(n % (base * 10) - base + 1, 0), base)

where 'base' is the position value (1 for ones, 10 for tens, 100 for hundreds, etc.).

By calculating the count for each position and summing them up, we can find the total occurrences of digit 'd' in the range [0, n].

Solution Code

class Solution {
    public int digitsCount(int d, int low, int high) {
        return countDigit(d, high) - countDigit(d, low - 1);
    }

    private int countDigit(int d, int n) {
        if (d == 0 && n == 0) return 1;
        int count = 0;
        for (long base = 1; base <= n; base *= 10) {
            long quotient = n / (base * 10);
            long remainder = n % (base * 10);
            count += quotient * base;
            count += Math.min(Math.max(remainder - d * base + 1, 0), base);
            if (d == 0) count -= base;
        }
        return count;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1067 (Digit Count in Range)?

This page provides optimized solutions for LeetCode problem 1067 (Digit Count in Range) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1067 (Digit Count in Range)?

The time complexity for LeetCode 1067 (Digit Count in Range) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1067 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1067 in Java, C++, or Python.

Back to LeetCode Solutions