Number Of Times Digit 3 Occurs In Each And Every Number From 0 To N In Java
This article explains how to count the occurrences of the digit '3' in every number from 0 up to a given integer n. You will learn different approaches to solve this problem efficiently in Java.
Problem Statement
The task is to determine how many times the digit '3' appears in each number within the range of 0 to n (inclusive). For example, if n is 15, we need to count '3' in 0, 1, 2, ..., 15. The number 3 has one '3', and the number 13 has one '3'.
Example
If n = 15, the count of digit '3' in each number from 0 to 15 would be:
- 0: 0
- 1: 0
- 2: 0
- 3: 1
- 4: 0
- 5: 0
- 6: 0
- 7: 0
- 8: 0
- 9: 0
- 10: 0
- 11: 0
- 12: 0
- 13: 1
- 14: 0
- 15: 0
The total count of '3's would be 2.
Background & Knowledge Prerequisites
To understand this article, you should be familiar with:
- Basic Java syntax (loops, conditional statements).
- Integer manipulation (modulo operator
%, division/). - Method creation and calling.
Use Cases or Case Studies
- Data Analysis: Counting specific digits can be useful in analyzing numerical patterns in datasets.
- Educational Tools: Developing exercises or tools for understanding number properties.
- Game Development: Implementing certain game mechanics that depend on digit occurrences.
- Algorithm Practice: A common interview question to test basic programming logic.
Solution Approaches
We will explore two main approaches to solve this problem.
Approach 1: Iterating and Digit Extraction
This approach involves iterating through each number from 0 to n and, for each number, extracting its digits to check if it's a '3'.
One-line summary
Iterate from 0 ton, convert each number to a string, and count '3's, or use arithmetic operations to extract digits.
Code example
// 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();
}
}
Sample output
Enter a non-negative integer (n): 15
Total occurrences of digit '3' from 0 to 15: 2
Stepwise explanation for clarity
- Get Input
n: The program prompts the user to enter an integern. - Initialize
totalCountOfThrees: A variable is set to 0 to keep track of the total occurrences of '3'. - Outer Loop (0 to
n): Aforloop iterates through each numberifrom 0 up ton. - Inner Loop (Digit Extraction):
- Inside the
forloop,currentNumberis assigned the value ofi. - A
whileloop then processescurrentNumberdigit by digit. -
currentNumber % 10extracts the last digit. If it's '3',totalCountOfThreesis incremented. -
currentNumber /= 10removes the last digit, effectively shifting the number to the right. - This continues until
currentNumberbecomes 0.
- Print Result: After checking all numbers, the final
totalCountOfThreesis printed.
Approach 2: Using String Conversion
This approach simplifies digit extraction by converting each number to a string and then iterating through its characters.
One-line summary
Convert each number from 0 ton into a string and count occurrences of the character '3'.
Code example
```java // Program Title: CountDigitThreeOccurrencesString 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++) { // Step 4: Convert the current number to a string String numberAsString = String.valueOf(i);
// Step 5: Iterate through the characters of the string for (char digitChar : numberAsString.toCharArray()) { if (digitChar == '3') { totalCountOfThrees++; } } }
// Step 6: Print the total count System.out.println("Total occurrences of digit '3' from 0