LeetCode 1922: Count Good Numbers Solution

Master LeetCode problem 1922 (Count Good Numbers), a medium 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.

1922. Count Good Numbers

Problem Explanation

Explanation

To solve this problem efficiently, we can use exponentiation by squaring to calculate the powers of 5 and 4 modulo 10^9 + 7. We can then use these powers to compute the total number of good digit strings of length n based on whether n is even or odd.

  • If n is even, the total number of good digit strings of length n is (pow(5, n/2) * pow(4, n/2)) % (10^9 + 7).
  • If n is odd, we need to consider an extra factor of 5 for the last digit, so the total number of good digit strings of length n is (pow(5, n/2) * pow(4, n/2) * 5) % (10^9 + 7).

Time complexity: O(log n)
Space complexity: O(1)

Solution Code

class Solution {
    public int countGoodNumbers(long n) {
        long mod = 1000000007;
        long res = 1;
        long power5 = 5;
        long power4 = 4;

        while (n > 0) {
            if ((n & 1) == 1) {
                res = (res * power5) % mod;
                n--;
            } else {
                power4 = (power4 * power4) % mod;
                n /= 2;
            }
        }

        return (int) res;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1922 (Count Good Numbers)?

This page provides optimized solutions for LeetCode problem 1922 (Count Good Numbers) 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 1922 (Count Good Numbers)?

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

Can I run code for LeetCode 1922 on DevExCode?

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

Back to LeetCode Solutions