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.
Constraints:
1 <= num <= 109num does not contain 0 as one of its digits.In this approach, we will convert the integer into a string to access each digit easily. We'll iterate through each digit, convert it back to an integer, and check if it divides the number using the modulus operation. This straightforward method handles each digit one by one and checks for divisibility.
The C solution makes use of a loop to repeatedly extract the last digit of the number using the modulus operator. It checks if this digit is a divisor of the original number. If so, it increases the count. Finally, it divides the number by 10 to remove the last digit and continues this process until all digits are checked.
C++
Java
Python
C#
JavaScript
Time Complexity: O(d), where d is the number of digits in the number.
Space Complexity: O(1), as no additional space is used.
This approach involves converting the number to a string and iterating over each character. By converting each character back to an integer, we can easily check if it divides the original number using the modulus operation. This simplifies digit handling, given the ease of iterating over strings in many programming languages.
Utilizes string manipulation functions to handle each digit. The integer is converted to a string form, facilitating easy conversion of individual characters back to integers for modulus checks.
C++
Java
Python
C#
JavaScript
Time Complexity: O(d), where d is the number of digits.
Space Complexity: O(d), used for string storage.
| Approach | Complexity |
|---|---|
| Approach 1: Iterative Check Using Modulus | Time Complexity: O(d), where d is the number of digits in the number. |
| Approach 2: Leveraging String Conversion | Time Complexity: O(d), where d is the number of digits. |
2520. Count the Digits That Divide a Number | Weekly Contest 326. • CODE with Rahul. • 1,470 views views
Watch 9 more video solutions →Practice Count the Digits That Divide a Number with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor