Problem Statement
Write a Java program to check how many times digit 1 occurs in a given number.
π Explanation (Simple Words)
We take a number from the user
Extract each digit using
% 10Check if the digit is equal to
1If yes, increase the count
Remove the last digit using
/ 10Repeat until the number becomes
0
π§ Algorithm
Start
Read the number
Initialize
count = 0While number ≠ 0
digit = number % 10
If digit == 1 → count++
number = number / 10
Print count
End
π» Java Program to Count Number of Ones
import java.util.Scanner;
public class CountOnes {
public static void main(String[] args) {
int number, count = 0;
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
number = sc.nextInt();
while (number != 0) {
int digit = number % 10;
if (digit == 1) {
count++;
}
number = number / 10;
}
System.out.println("Number of ones: " + count);
}
}
π§ͺ Dry Run
Input
number = 12131
count = 0
| Step | number | digit | count |
|---|---|---|---|
| 1 | 12131 | 1 | 1 |
| 2 | 1213 | 3 | 1 |
| 3 | 121 | 1 | 2 |
| 4 | 12 | 2 | 2 |
| 5 | 1 | 1 | 3 |
Final Output
Number of ones: 3
π₯️ Output
Enter a number: 12131
Number of ones: 3
π Important Points for Exams
% 10→ extracts last digit/ 10→ removes last digitWorks for any integer number
Time Complexity: O(n)
Comments
Post a Comment