Java Online Compiler
Example: CountDigitThreeOccurrences in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// CountDigitThreeOccurrences import java.util.Scanner; // Main class containing the entry point of the program public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Step 1: Get input 'n' from the user System.out.print("Enter a non-negative integer (n): "); int n = scanner.nextInt(); // Step 2: Initialize total count for digit '3' int totalCountOfThrees = 0; // Step 3: Loop through each number from 0 to n for (int i = 0; i <= n; i++) { int currentNumber = i; // Step 4: Count '3's in the current number while (currentNumber > 0) { if (currentNumber % 10 == 3) { totalCountOfThrees++; } currentNumber /= 10; } // Special case for number 0 if it contains '3' (not applicable here, but good practice) // For 0, the loop currentNumber > 0 won't run, so it correctly counts 0 '3's. } // Step 5: Print the total count System.out.println("Total occurrences of digit '3' from 0 to " + n + ": " + totalCountOfThrees); scanner.close(); } }
Output
Clear
ADVERTISEMENTS