C++ Program to Count Digits in a Number
while loop and incrementing a counter until the number becomes 0, like this: while (num != 0) { num /= 10; count++; }.Examples
How to Think About It
Algorithm
Code
#include <iostream> using namespace std; int main() { int num, count = 0; cout << "Enter a number: "; cin >> num; if (num == 0) { count = 1; } else { if (num < 0) num = -num; while (num != 0) { num /= 10; count++; } } cout << "Number of digits: " << count << endl; return 0; }
Dry Run
Let's trace the input 12345 through the code to count digits.
Input number
num = 12345, count = 0
Check if zero
num is not zero, continue
Check if negative
num is positive, no change
Start loop
num = 12345, count = 0
Divide and count
num = 1234, count = 1
Divide and count
num = 123, count = 2
Divide and count
num = 12, count = 3
Divide and count
num = 1, count = 4
Divide and count
num = 0, count = 5
Loop ends
num is zero, exit loop
| num | count |
|---|---|
| 12345 | 0 |
| 1234 | 1 |
| 123 | 2 |
| 12 | 3 |
| 1 | 4 |
| 0 | 5 |
Why This Works
Step 1: Handle zero input
If the number is zero, it has exactly one digit, so we set count to 1 immediately.
Step 2: Make number positive
If the number is negative, convert it to positive because digit count is the same for negative numbers.
Step 3: Count digits by division
Each time we divide the number by 10, we remove the last digit and increase the count until the number becomes zero.
Alternative Approaches
#include <iostream> #include <string> using namespace std; int main() { int num; cout << "Enter a number: "; cin >> num; string s = to_string(num < 0 ? -num : num); cout << "Number of digits: " << s.length() << endl; return 0; }
#include <iostream> #include <cmath> using namespace std; int main() { int num; cout << "Enter a number: "; cin >> num; if (num == 0) { cout << "Number of digits: 1" << endl; } else { num = abs(num); int count = (int)log10(num) + 1; cout << "Number of digits: " << count << endl; } return 0; }
Complexity: O(d) time, O(1) space
Time Complexity
The loop runs once for each digit, so time grows linearly with the number of digits d.
Space Complexity
Only a few variables are used, so space is constant O(1).
Which Approach is Fastest?
The division loop and logarithm methods are both fast; the string method uses extra memory and is slower for very large numbers.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Division loop | O(d) | O(1) | Simple and memory efficient |
| String conversion | O(d) | O(d) | Easy to implement, less efficient |
| Logarithm method | O(1) | O(1) | Fastest for large numbers, needs math library |