Is there any efficient way to find out the count of distinct digits from a given number in constant time or O(Logn)?
Suppose n = 1234
the count should be 4
(As there are 4
distinct digits)
if n = 1121
the count should be 2
(As there are 2
distinct digits i.e 1, 2
)
Constraint: 0 <= n <= 1000000007
Pseudo-code:
int DistinctDigits(int n)
{
int result = 0;
bool[10] digitFound = {false};
while (n > 0)
{
d = n % 10;
n = n / 10;
if (!digitFound[d])
{
result++;
digitFound[d] = true;
}
}
return result;
}
Note that you have to think about what to do with leading zeroes (including when n == 0).