How to check if an integer include specific digits x times in Java

1 Answer

0 votes
public class Main {
    // Method to check digit occurrences
    public static boolean checkDigitOccurrences(int n, int xtims, int digit) {
        int count = 0;

        // Count occurrences of the digit in the number
        while (n > 0) {
            if (n % 10 == digit) {
                count++;
            }
            n = n / 10;
        }

        // Return true if count matches xtims
        return count == xtims;
    }

    public static void main(String[] args) {
        // Test the function with given inputs
        System.out.println(checkDigitOccurrences(7097175, 3, 7)); 
        System.out.println(checkDigitOccurrences(70975, 3, 7));  
    }
}


/*
run:

true
false

*/

 



answered Apr 26, 2025 by avibootz
...