Similar Problems

Similar Problems not available

Count The Digits That Divide A Number - Leetcode Solution

Companies:

LeetCode:  Count The Digits That Divide A Number Leetcode Solution

Difficulty: Easy

Topics: math  

Problem statement: Given an integer n, return the number of digits that are a proper divisor of n. A proper divisor is a positive integer that divides n evenly but is not equal to n.

Example 1: Input: n = 12 Output: 2 Explanation: The proper divisors of 12 are 1, 2, 3, 4, and 6. Of these, only 2 and 3 are digits in 12.

Example 2: Input: n = 1012 Output: 3 Explanation: The proper divisors of 1012 are 1, 2, 4, 253, 506, and 1012. Of these, only 1, 2, and 4 are digits in 1012.

Solution: The approach to solving this problem would be to first find all the factors of n which are smaller than it. Then for each factor, we check if the digit is present in the number. If it is, we increment a counter.

To accomplish this task, we can use a simple for loop to iterate over all the numbers from 1 to n-1. We then use the modulus operator to check if the current number is a factor of n. If yes, we count the number of digits in the factor and check if each digit is present in n using a nested loop. If we find a digit that is present in n, we increment the counter.

Here is the code for this approach:

class Solution {
public:
    int countDigits(int n) {
        int count = 0;
        
        for (int i = 1; i < n; i++) {
            if (n % i == 0) {
                int num = i;
                while (num > 0) {
                    int digit = num % 10;
                    num /= 10;
                    if (digit != 0 && n % digit == 0) {
                        count++;
                    }
                }
            }
        }
        return count;
    }
};

Time Complexity: The time complexity of this solution is O(n^2) since we are iterating over all the numbers from 1 to n-1 and also checking each digit in each factor.

Space Complexity: The space complexity of this solution is O(1) since we are not storing any extra data.

Count The Digits That Divide A Number Solution Code

1