Difficulty: 🟢 Easy
Given an integer num
, return the number of digits in num
that divide num
.
An integer val
divides nums if nums % val == 0
.
Example 1:
Input: num = 7
Output: 1
Explanation: 7 divides itself, hence the answer is 1.
Example 2:
Input: num = 121
Output: 2
Explanation: 121 is divisible by 1, but not 2. Since 1 occurs twice as a digit, we return 2.
Example 3:
Input: num = 1248
Output: 4
Explanation: 1248 is divisible by all of its digits, hence the answer is 4.
1 <= num <= 109
num
does not contain0
as one of its digits.
class Solution:
def countDigits(self, num: int) -> int:
original, total = num, 0
while num:
n = num % 10
total += 0 if original % n else 1
num //= 10
return total
The given solution solves the problem by performing the following steps:
- Initialize
original
asnum
andtotal
as 0. - Iterate through each digit of
num
by dividingnum
by 10 in each iteration untilnum
becomes 0.- Get the current digit
n
by takingnum % 10
. - Check if
original % n == 0
.- If true, increment
total
by 1. - If false, continue to the next iteration.
- If true, increment
- Divide
num
by 10 to move to the next digit.
- Get the current digit
- After the loop ends, return the value of
total
as the count of digits innum
that dividenum
.
The time complexity of this algorithm is O(log num) because we iterate through each digit of num
.
The space complexity of the algorithm is O(1) because we only use a constant amount of space to store the variables original
, total
, and n
.
The given solution counts the number of digits in num
that divide num
. It iterates through each digit of num
and checks if the digit divides num
. It maintains a count of such digits and returns the count at the end. The algorithm has a time complexity of O(log num) and a space complexity of O(1), making it efficient for the given constraints.
NB: If you want to get community points please suggest solutions in other languages as merge requests.