Given an integer N, count how many digits are present in it.
Only the digits should be counted. If the number is negative, the minus sign is not a digit.
Example 1
Input: n = 1567
Output: 4
Explanation: The digits are 1, 5, 6, and 7, so the count is 4.
Example 2
Input: n = -980
Output: 3
Explanation: The minus sign is not counted. The digits are 9, 8, and 0.
Approach
The first observation is very direct: every time a number is divided by 10 using integer division, its last digit disappears.
For example, if the number is 1567, then:
1567 -> 156 -> 15 -> 1 -> 0
This is the key pattern. Each step removes exactly one digit, so if the number of steps is counted until the number becomes 0, that count is the answer.
The only special case is 0 itself. Even though the loop would not run for it, the number 0 still has one digit, so that case must be handled separately.
If negative numbers are allowed, the sign does not matter because only the digits are being counted. So the number can be made positive first and then processed normally.
Algorithm
First, make the number positive by taking its absolute value. This is done because only the digits matter here, not the minus sign.
Handle the case
N = 0separately by returning1, because0itself is a one-digit number.Keep a variable
countas0. In the beginning, no digit has been removed yet.Repeatedly divide the number by
10using integer division. This step is useful because each division removes exactly one last digit.After each removal, increase
countby1so the answer remembers how many digits have disappeared so far.Keep doing this until the number becomes
0, because at that point every digit has been removed and counted.Return
countas the final answer.
Key Points
0has exactly one digit.If negative numbers are allowed, count the digits of the absolute value.
Dry Run
Count Digits Dry Run
Solution
#include <bits/stdc++.h>using namespace std;class Solution {public: /* Returns how many digits are present in n. */ int countDigits(int n) { // Uses the absolute value because the minus sign is not a digit. long long num = llabs((long long)n); // The number 0 still has one digit, so handle it separately. if (num == 0) { return 1; } // Stores how many digits have been removed so far. int count = 0; // Keep removing digits until the number becomes empty. while (num > 0) { // Integer division by 10 removes the current last digit. num /= 10; // Increase answer as one more digit processed. count++; } return count; }};// Driver code startsint main() { int n = -980; Solution obj; cout << obj.countDigits(n) << endl; return 0;}Output:
Complexity Analysis
Time Complexity: O(log10 N), because one digit is removed in each iteration.
Space Complexity: O(1), because constant space is used.
Interview follow-up Questions
Because 0 is a one-digit number, but the loop would not run even once for it.
Be the first to add a comment.