easyBasic Math Concepts
Count Digits
Count the decimal digits in a nonnegative integer. Zero has one digit.
Work through the cases
3 examplesInput notation
An integer from 0 through 1000000000.Expected result
The digit count.Case 1
Input
4072
Expected output
4
Case 2
Input
0
Expected output
1
Case 3
Input
1000000000
Expected output
10
These notes use simplified input/output notation. The linked platform defines the method signature and judge format.
FROM IDEA TO IMPLEMENTATION
Understand the approach.
Compare the documented approaches below. Brute force, better, and optimal versions appear where available; a direct exercise may need only one approach.
Divide by 10 repeatedly. Handle zero as one digit. Time: O(d), where d is the digit count. Extra space: O(1).
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ArrayList<Long> values = new ArrayList<>();
while (in.hasNextLong()) values.add(in.nextLong());
long[] a = values.stream().mapToLong(Long::longValue).toArray();
long n = a[0];
int count = 1; while (n >= 10) { n /= 10; count++; } System.out.println(count);
}
}
Reference code. Platform solutions may use supplied node types, imports, or collection libraries; foundational examples are complete programs.