algoadvance

Leetcode 2520. Count the Digits That Divide a Number

Problem Statement

You are given a positive integer num. Return the number of digits in num that divide num.

A digit divides num if num % digit == 0.

Clarifying Questions

  1. Can num have zeroes as digits?
    • No, since a digit of zero does not divide any number, the problem constraints must ensure digits are from 1-9. If not, we ignore zeros while counting.
  2. What’s the value range of num?
    • Assuming it’s within typical integer limits unless specified otherwise (e.g., up to (2^{31}-1) for 32-bit signed integer).
  3. Is num guaranteed to be positive?
    • Yes, the problem specifies num as a positive integer.

Strategy

  1. Convert the number to its string representation to easily iterate through each digit.
  2. For each digit, convert it back to an integer and check if it divides num.
  3. Count how many digits satisfy this condition.
  4. Return the count.

Code

Here is the solution in Java:

public class CountDividingDigits {
    public int countDigits(int num) {
        int count = 0;
        int originalNum = num;
        
        while (num > 0) {
            int digit = num % 10;
            if (digit != 0 && originalNum % digit == 0) {
                count++;
            }
            num /= 10;
        }
        
        return count;
    }

    public static void main(String[] args) {
        CountDividingDigits solution = new CountDividingDigits();
        int num = 121; // Example number
        int result = solution.countDigits(num);
        System.out.println("Number of digits in " + num + " that divide it is: " + result);
    }
}

Explanation

  1. Initial Setup:
    • We initialize a counter to zero.
    • Store the original number for modulus operations.
  2. Extracting and Checking Digits:
    • Use a loop to process each digit by taking the modulus 10 (num % 10) to get the last digit.
    • Check if the digit is non-zero and if it divides the original number without a remainder.
    • If true, increment the counter.
  3. Updating the Number:
    • Use integer division by 10 (num /= 10) to remove the last digit.
    • Continue until all digits are processed.
  4. Return Counter:
    • Return the count of digits that divide the original number.

Time Complexity

This approach ensures efficient and clear handling of the problem requirements.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI