DEV Community

SoftwareDev
SoftwareDev

Posted on

πŸ”’ Today I Learned: Counting Digits in Java

Today I learned how to count how many times a particular digit appears in a number using Java β˜•

πŸ’» The Code

import java.util.Scanner;

public class DigitCount {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.println("Enter a number: ");
        int N = sc.nextInt();

        System.out.println("Enter a digit to count: ");
        int D = sc.nextInt();

        int count = 0;

        while (N > 0) {
            int lastDigit = N % 10; // extract last digit
            if (lastDigit == D) {
                count++;
            }
            N = N / 10; // remove last digit
        }

        System.out.println("Digit " + D + " appears " + count + " times.");
        sc.close();
    }
}
Enter fullscreen mode Exit fullscreen mode

πŸ”Ž How It Works

  • Take input N (the number) and D (the digit to count).
  • Initialize count = 0.
  • Loop while N > 0:
  • Extract the last digit using % 10.
  • Compare it with D. If equal β†’ increment count.
  • Remove the last digit using / 10.
  • Print the final count.

This is a very simple and logical approach to digit problems, and it feels quite mathematical.
I loved solving it πŸ’‘

πŸš€ Alternative Approaches

There are many ways to solve this same problem:

  1. String Conversion

Convert the number to a string β†’ loop over characters β†’ compare with the digit.

String str = String.valueOf(N);
long count = str.chars().filter(ch -> ch == (D + '0')).count();

This approach uses Java Streams.

  1. Recursion

You can solve it with recursion by checking the last digit and then calling the method with N / 10.

  1. Arrays / Collections

Extract digits into an array/list and count with a loop or streams.

❓ Discussion

Which method do you prefer for solving such problems?
➑️ Math-based loops (% and /)
➑️ String-based tricks

🏷️ Suggested Tags

java #beginners #tutorial #problem-solving

Top comments (0)