Given an integer num
, return the number of digits in num
that divide num
.
A digit divides num
if num % digit == 0
.
Example:
Input: num = 121
Output: 2
Explanation: 121 is divisible by its digit 1, but not by its digit 2. Thus, 2 digits divide 121.
Constraints:
d
is the number of digits in num
. Given the constraint, the maximum number of digits is 10, so it’s a constant time operation in practice.def count_digits(num: int) -> int:
count = 0
for digit in str(num):
if digit != '0' and num % int(digit) == 0:
count += 1
return count
# Test cases
print(count_digits(121)) # Output: 2
print(count_digits(12345)) # Output: 2 (1 and 5 divide 12345)
print(count_digits(100)) # Output: 1 (only 1 divides 100)
num
to a string to iterate over each digit.'0'
(skip it) and if the digit divides num
.This approach ensures we account for all digits and their divisibility while handling the potential issue of division by zero.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?