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();
}
}
π 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:
- 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.
- Recursion
You can solve it with recursion by checking the last digit and then calling the method with N / 10.
- 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
Top comments (0)