Count the Digits That Divide a Number
EasyUpdated: Aug 2, 2025
Practice on:
Problem
Given an integer num, return _the number of digits innum that divide _num.
An integer val divides nums if nums % val == 0.
Examples
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.
Constraints
1 <= num <= 10^9numdoes not contain0as one of its digits.
Solution
Method 1 – Digit Check and Count
Intuition
For each digit in the number, check if it divides the number. Since the number does not contain 0 as a digit, we can safely check divisibility for each digit.
Approach
- Convert the number to a string or process its digits one by one.
- For each digit, check if
num % digit == 0. - Count the number of such digits.
- Return the count.
Code
C++
class Solution {
public:
int countDigits(int num) {
int ans = 0, n = num;
while (n > 0) {
int d = n % 10;
if (num % d == 0) ans++;
n /= 10;
}
return ans;
}
};
Go
type Solution struct{}
func (Solution) CountDigits(num int) int {
ans, n := 0, num
for n > 0 {
d := n % 10
if num%d == 0 {
ans++
}
n /= 10
}
return ans
}
Java
class Solution {
public int countDigits(int num) {
int ans = 0, n = num;
while (n > 0) {
int d = n % 10;
if (num % d == 0) ans++;
n /= 10;
}
return ans;
}
}
Kotlin
class Solution {
fun countDigits(num: Int): Int {
var ans = 0
var n = num
while (n > 0) {
val d = n % 10
if (num % d == 0) ans++
n /= 10
}
return ans
}
}
Python
class Solution:
def countDigits(self, num: int) -> int:
ans = 0
n = num
while n > 0:
d = n % 10
if num % d == 0:
ans += 1
n //= 10
return ans
Rust
impl Solution {
pub fn count_digits(num: i32) -> i32 {
let mut ans = 0;
let mut n = num;
while n > 0 {
let d = n % 10;
if num % d == 0 {
ans += 1;
}
n /= 10;
}
ans
}
}
TypeScript
class Solution {
countDigits(num: number): number {
let ans = 0, n = num;
while (n > 0) {
const d = n % 10;
if (num % d === 0) ans++;
n = Math.floor(n / 10);
}
return ans;
}
}
Complexity
- ⏰ Time complexity:
O(log_{10} n), since we process each digit of the number. - 🧺 Space complexity:
O(1), only a few variables are used.