Problem overview
The method noOfDigits receives a non-negative integer n and returns how many digits it is written with. The number 542 has 3 digits, 100 has 3 (the zeros count), and 0 has exactly 1.
Approach
Dividing a number by 10 and dropping the fraction removes its last digit: 542 becomes 54, then 5, then 0. The number of divisions needed to reach 0 is the number of digits. So the method counts turns of a loop that divides n by 10 until n is 0.
The one number this idea cannot handle is 0 itself. The loop runs only while n is greater than 0, so for 0 it would count nothing and return 0, though 0 is written with one digit. The method deals with it first, before the loop.
In TypeScript, 542 / 10 is 54.2, because / divides doubles. Math.floor rounds the result down to 54, which is what removing the last digit means for a non-negative number.
Step by step
- Handle zero. If
n === 0, return 1 immediately. - Declare
countwithletas anumber, starting at 0. It changes in the loop, so it can't beconst. - Write a
whileloop that runs as long asn > 0. It turns once per digit. - Count the digit with
count++. - Drop the last digit:
n = Math.floor(n / 10). When every digit is gone,nis 0 and the loop stops. - Return
countafter the loop.
The solution in TypeScript
class Solution {
noOfDigits(n: number): number {
if (n === 0) {
return 1;
}
let count: number = 0;
while (n > 0) {
count++;
n = Math.floor(n / 10);
}
return count;
}
}
===compares without converting. It is the usual equality operator in TypeScript. The looser==converts types before comparing, and the compiler would still accept it, but===is the habit to keep.- The parameter can be reassigned. Changing
ninside the method does not change the caller's number. - The types are labels.
numberis erased when the code is compiled to JavaScript, and anumberis a double, not an integer type. That is whyMath.flooris needed to get integer division.
Complexity
Time: O(log n). Each turn divides n by 10, so the loop turns once per digit. For values up to 10^9 that is at most 10 turns.
Space: O(1). Only count and the parameter are used.
Edge cases and common mistakes
- Zero. Without the early return the answer for 0 would be 0. With it, the answer is 1.
- Trailing zeros. 100 gives 3: the divisions give 10, then 1, then 0, which is three turns.
- The largest input. 1000000000 has 10 digits, and the function returns 10.
- Forgetting
Math.floor.n / 10leaves a fraction, so 542 becomes 54.2, 5.42, 0.542 and so on. The loop then runs many more turns than there are digits and the count is wrong. - Counting after the division. Placing
count++anywhere outside the loop, or returningcountinside it, stops the count at one digit.
Testing
n = 542gives3.n = 100gives3.n = 0gives1.n = 9gives1.n = 1000000000gives10.
