Practice › Basics
Count Digits
Easy · Basics · Asked at TCS, Infosys, Wipro, Accenture, Cognizant
Print how many digits the non-negative integer n has.
Input
One integer n (no leading zeros).
Output
The number of digits.
Constraints
- 0 ≤ n ≤ 10^18
0has 1 digit.10^18does not fit in a 32-bit int.
Example 1
Input
12345
Output
5
Example 2
Input
0
Output
1
Hints
- Keep dividing n by 10 until it becomes 0 and count the steps.
- Special case: 0 has one digit, but the loop runs zero times for it.
Approach
Each division by 10 removes the last digit, so the number of divisions until n reaches 0 is the digit count. Handle n = 0 separately (answer 1). Use a 64-bit type because n can be 10^18. In Python, len(str(n)) does the same job.
Complexity: O(number of digits) time · O(1) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
long long n;
cin >> n;
int digits = 0;
do {
digits++;
n /= 10;
} while (n > 0);
cout << digits << "\n";
return 0;
}Python solution
n = input().strip()
print(len(str(int(n))))Java solution
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
long n = sc.nextLong();
int digits = 0;
do {
digits++;
n /= 10;
} while (n > 0);
System.out.println(digits);
}
}