Difficulty: Easy | Acceptance: 85.90% | Paid: No Topics: Math
Given an integer num, return the number of digits in num that divide num.
An integer val divides nums if nums % val == 0.
- Examples
- Constraints
- Iterative Approach
- String Conversion Approach
Examples
Example 1:
Input: num = 7
Output: 1
Explanation: 7 divides 7, so 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, so the answer is 4.
Constraints
1 <= num <= 10⁹
Iterative Approach
Intuition Extract each digit from the number using modulo and division operations, then check if each digit divides the original number.
Steps
- Store the original number in a temporary variable
- Iterate through each digit by taking modulo 10
- Check if the digit divides the original number
- Divide the temporary number by 10 to move to the next digit
- Count the digits that divide the number
python
class Solution:
def countDigits(self, num: int) -> int:
original = num
count = 0
while num > 0:
digit = num % 10
if original % digit == 0:
count += 1
num //= 10
return countComplexity
- Time: O(log n) where n is the number of digits in num
- Space: O(1)
- Notes: This is the most efficient approach with constant space complexity.
String Conversion Approach
Intuition Convert the number to a string and iterate through each character, converting it back to an integer to check divisibility.
Steps
- Convert the number to a string
- Iterate through each character in the string
- Convert each character back to an integer
- Check if the digit divides the original number
- Count the digits that divide the number
python
class Solution:
def countDigits(self, num: int) -> int:
count = 0
for digit in str(num):
if num % int(digit) == 0:
count += 1
return countComplexity
- Time: O(log n) where n is the number of digits in num
- Space: O(log n) for storing the string representation
- Notes: Slightly less space-efficient than the iterative approach but more readable.