Count Digits of a Number
Problem
Read an integer and print how many digits it has. Ignore the minus sign. The number 0 has 1 digit.
Constraints
- -10^18 <= n <= 10^18
Examples
Input
12345
Output
5
Input
0
Output
1
Solutions
Each division by 10 removes exactly one digit, so the number of divisions until we reach 0 is the digit count. Zero is a special case.
/*
* Problem : Count the digits of an integer.
* Input : One integer.
* Output : The number of digits.
* Approach: Divide by 10 until the number is 0.
* Time : O(d)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
long number = Math.abs(new Scanner(System.in).nextLong());
// Step 1: Zero has one digit. The loop below would count 0 digits, so we handle it first.
if (number == 0) {
System.out.println(1);
return;
}
// Step 2: Start the counter at 0.
int count = 0;
// Step 3: Repeat until the number becomes 0.
while (number > 0) {
// Step 4: Remove the last digit. Example: 12345 / 10 = 1234.
number = number / 10;
// Step 5: Count the removed digit.
count++;
}
// Step 6: Print the count.
System.out.println(count);
}
}
Hints (2)
- How many times can you divide 12345 by 10 before you reach 0?
- What happens for the input 0?