I was practicing from Leetcode earlier and I came across this question:
Given an integer num, return the number of 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.
ShraavaniJha is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
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 (num % lastdigit == 0)
{
s.insert(lastdigit);
}
n /= 10;
}
return s.size();
}
};