Leetcode 2520. Count the Digits That Divide a Number
You are given a positive integer num
. Count the number of digits in num
that divide num
.
A digit divides num
if num % digit == 0
.
Return the number of digits that divide num
.
num
?
num
is a positive integer. Let’s assume it fits within the range of standard integer types in C++.num
?
num
will be a non-zero positive integer?
num
to its string representation to easily iterate over each digit.num
.num
is divisible by this digit.#include <iostream>
#include <string>
int countDigitsThatDivide(int num) {
std::string numStr = std::to_string(num);
int count = 0;
for (char c : numStr) {
int digit = c - '0'; // Convert char to int
if (digit != 0 && num % digit == 0) {
count++;
}
}
return count;
}
int main() {
int num = 124; // Example input
std::cout << "Number of digits in " << num << " that divide the number: " << countDigitsThatDivide(num) << std::endl;
return 0;
}
The time complexity of this solution is O(d), where d
is the number of digits in num
. This is because we are performing a single pass through each digit in the number.
The space complexity is O(1) excluding the input and output because we only use a few extra variables regardless of the size of num
.
This solution effectively handles the problem requirements and constraints as specified.
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?