c++mathintegermodulodigits

Counting the number of distinct digits that divide a number- Unable to pass all test cases


I was practicing from Leetcode earlier and I came across this question:

Given an integer num, return the number of distinct digits in num that divide num. An integer val divides nums if nums % val == 0.

I came up with the following approach and even though it ran for a few sample test cases, when I submitted it it couldn't clear test cases such as 54, where the output should be 0 but with my code the output is 1.

class Solution {
public:
    int countDigits(int num) {
        set<int> s;
        while (num > 0)
        {
            int lastdigit = num % 10;
            if (num % lastdigit == 0)
            {
                s.insert(lastdigit);
            }
            num /= 10;
        }
        if (s.empty()) {
            return 0;
        } else {
            return s.size();
        }
    }
};

I have attached my code for reference, please help me find out where I'm faltering.


Solution

  • The problem is that you are changing num, but when you do the test num % lastdigit == 0 you want to be using the original value of num.

    Your code will also fail with a division by zero error if the input has a zero digit, num % lastdigit is not legal if lastdigit is zero.

    Also no need to test for an empty set, what do you think s.size() will return if s is empty?

    Here's the fixed code

    class Solution {
    public:
        int countDigits(int num) {
            set<int> s;
            int n = num;
            while (n > 0)
            {
                int lastdigit = n % 10;
                if (lastdigit != 0  && num % lastdigit == 0)
                {
                    s.insert(lastdigit);
                }
                n /= 10;
            }
            return s.size();
        }
    };
    

    There's one other possible issue, what should 44 return? If you think the answer is two, then your code has another bug, because four will not get added to the set twice. If that's an issue you should just use a integer variable to count the number of digits. Like this

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