LeetCode 3490: Count Beautiful Numbers Solution

Master LeetCode problem 3490 (Count Beautiful Numbers), 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.

3490. Count Beautiful Numbers

Problem Explanation

Explanation:

To solve this problem, we can iterate through each number from l to r (inclusive), calculate the product and sum of its digits, and check if the product is divisible by the sum. If it is, then the number is considered beautiful and we increment the count.

Algorithm:

  1. Define a helper function to calculate the product of digits.
  2. Define a helper function to calculate the sum of digits.
  3. Initialize a variable count to 0.
  4. Iterate through each number from l to r.
  5. For each number, calculate the product and sum of its digits.
  6. If the product is divisible by the sum, increment the count.
  7. Return the count as the result.

Time Complexity: O((r-l) * log(r)) Space Complexity: O(1)

:

Solution Code

class Solution {
    public int countBeautifulNumbers(int l, int r) {
        int count = 0;
        for (int i = l; i <= r; i++) {
            int product = getProductOfDigits(i);
            int sum = getSumOfDigits(i);
            if (product % sum == 0) {
                count++;
            }
        }
        return count;
    }
    
    private int getProductOfDigits(int num) {
        int product = 1;
        while (num > 0) {
            product *= num % 10;
            num /= 10;
        }
        return product;
    }
    
    private int getSumOfDigits(int num) {
        int sum = 0;
        while (num > 0) {
            sum += num % 10;
            num /= 10;
        }
        return sum;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 3490 (Count Beautiful Numbers)?

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

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

Can I run code for LeetCode 3490 on DevExCode?

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

Back to LeetCode Solutions