Problem overview
The function noOfDigits receives a non-negative integer n and returns how many digits it is written with. 542 has 3 digits, and 100 has 3 too, because zeros are digits. The number 0 is a special case: it is written with one digit, so the answer is 1.
Approach
Dividing an int by 10 with / drops the remainder, which removes the last digit: 542 becomes 54. Count how many times you can do that before the number reaches 0, and you have the number of digits. Go has no while, so the repeat is a for loop with only a condition: for n > 0.
That count is right for every positive number but wrong for 0, where the loop wouldn't run at all and the count would stay 0. So 0 gets its own early return.
For n = 542, the values after each pass are:
| Pass | n afterwards | count |
|---|---|---|
| 1 | 54 | 1 |
| 2 | 5 | 2 |
| 3 | 0 | 3 |
Step by step
- Handle zero first. If
n == 0, return 1. The loop below only runs while the number is greater than 0, so it would count no digits for 0. - Create
countwith:=, starting at 0. No digit has been removed yet. - Write the loop with the condition
n > 0, and its closing brace right away. Each pass removes one digit. - Add 1 to
countwith++. One pass is one digit. - Drop the last digit with
n = n / 10. Once every digit is gone,nis 0 and the loop stops. - Return
countafter the loop.
The solution in Go
func noOfDigits(n int) int {
if n == 0 {
return 1
}
count := 0
for n > 0 {
count++
n = n / 10
}
return count
}
Go details:
count++is a statement. In Go,++can't be used inside an expression, sox := count++doesn't compile. It stands on its own line.- Integer division. Both operands are
int, so/truncates.542 / 10is 54, not 54.2. - The parameter is a copy. Changing
ninside the function doesn't affect the caller.
Complexity
The loop runs once per digit, so the time grows with the number of digits, and the space is one counter. For inputs up to a billion, that is at most ten passes.
Another way
You can also turn the number into text and measure it. In a file of your own, with strconv imported, len(strconv.Itoa(n)) gives 3 for 542, 3 for 100, 1 for 0 and 10 for 1000000000, so it needs no special case for 0. The lesson uses the division loop because it practises for and integer arithmetic, and it never builds a string.
Edge cases and common mistakes
- Zero. Without the early return,
noOfDigits(0)gives 0 instead of 1. - Zeros inside and at the end.
noOfDigits(100)returns 3, because each division removes one digit regardless of its value. - Largest input.
noOfDigits(1000000000)returns 10. - Forgetting to update
n. If the division line is missing, the loop never ends for a positiven.
Testing
542gives 3.100gives 3.0gives 1.7gives 1.1000000000gives 10.
