Count the Digits That Divide a Number - Problem

Given an integer num, return the number of digits in num that divide num.

An integer val divides nums if nums % val == 0.

Note: We cannot divide by zero, so digits equal to 0 should be ignored.

Input & Output

Example 1 — Basic Case
$ Input: num = 121
Output: 2
💡 Note: 121 has digits 1, 2, 1. Digit 1 divides 121 (121/1 = 121), digit 2 does not divide 121 (121/2 = 60.5), digit 1 divides 121. So 2 digits divide 121.
Example 2 — All Digits Divide
$ Input: num = 1248
Output: 4
💡 Note: 1248 has digits 1, 2, 4, 8. All digits divide 1248 evenly: 1248/1=1248, 1248/2=624, 1248/4=312, 1248/8=156. So all 4 digits divide the number.
Example 3 — Zero Digit
$ Input: num = 1012
Output: 3
💡 Note: 1012 has digits 1, 0, 1, 2. We ignore 0 (can't divide by zero). Digits 1, 1, and 2 all divide 1012 evenly, so count is 3.

Constraints

  • 1 ≤ num ≤ 109
  • num does not contain 0 as a digit in most test cases

Visualization

Tap to expand
Count the Digits That Divide a Number INPUT Number: num = 121 1 digit[0] 2 digit[1] 1 digit[2] String: "121" Length: 3 digits Input Value num = 121 Digits to check: [1, 2, 1] Check if 121 % digit == 0 ALGORITHM STEPS 1 Convert to String "121" to iterate digits 2 Check Each Digit Skip if digit == 0 3 Test Divisibility num % digit == 0 ? 4 Count Matches Increment counter Divisibility Check 121 % 1 = 0 OK 121 % 2 = 1 FAIL 121 % 1 = 0 OK Count: 2 digits divide 121 FINAL RESULT Digits that divide 121: 1 divides 1 divides 2 no divide Output 2 2 digits divide num Key Insight: Convert the number to a string to easily iterate through each digit. For each digit (skip zeros), check if num % digit == 0. Count all digits that satisfy this condition. Time: O(d), Space: O(d) TutorialsPoint - Count the Digits That Divide a Number | String Conversion Approach
Asked in
Amazon 25 Microsoft 15
28.0K Views
Medium Frequency
~10 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen