๐ง What Does "Counting Digits" Mean?
Counting digits means finding how many individual digits a number has.
For example:
-
The number 12345 has 5 digits.
-
The number 9 has 1 digit.
-
The number 0 has 1 digit.
๐น Method 1: Using While Loop (Division Method)
This method repeatedly divides the number by 10 until it becomes 0.
Each division removes one digit, and we count how many times this happens.
✅ Java Program
import java.util.Scanner;
public class CountDigitsLoop {
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();
int temp = number; // store the original number
// handle zero separately
if (number == 0) {
count = 1;
} else {
// convert negative number to positive
if (number < 0)
number = -number;
// count digits
while (number > 0) {
number = number / 10;
count++;
}
}
System.out.println("The number of digits in " + temp + " is: " + count);
sc.close();
}
}
๐งฉ How It Works
-
Take a number from the user.
-
If it’s negative, convert it to positive.
-
Divide the number by 10 repeatedly until it becomes 0.
-
Count the number of divisions — that’s the total digits.
๐งพ Example Output
Enter a number: 45217
The number of digits in 45217 is: 5
Enter a number: -98
The number of digits in -98 is: 2
๐น Method 2: Using String Conversion
This method is simpler and doesn’t use loops.
We just convert the number into a string and count how many characters it has.
✅ Java Program
import java.util.Scanner;
public class CountDigitsString {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = sc.nextInt();
// Convert to string and take absolute value for negatives
String numStr = Integer.toString(Math.abs(number));
// Length of the string = number of digits
int count = numStr.length();
System.out.println("The number of digits in " + number + " is: " + count);
sc.close();
}
}
๐งฉ How It Works
-
The user enters a number.
-
The number is converted to a string using
Integer.toString(). -
We find the length of that string using
.length(). -
The result gives the total number of digits.
๐งพ Example Output
Enter a number: 98765
The number of digits in 98765 is: 5
Enter a number: -123
The number of digits in -123 is: 3
⚖️ Comparison Between Both Methods
| Feature | Loop Method | String Method |
|---|---|---|
| Logic Type | Mathematical | String-based |
| Uses Loop | ✅ Yes | ❌ No |
| Handles Negative Numbers | ✅ Yes | ✅ Yes |
| Code Length | Medium | Short |
| Best For | Beginners learning loops | Quick and clean code |
๐ Conclusion
Both methods are correct — the loop method helps understand number operations, while the string method is more concise.
๐ Use the loop method for learning and the string method for quick coding tasks.
Comments
Post a Comment