11 Digit Counting
There are many situations in which a program needs to know the number of digits in an int
. Unfortunately, int
variables don’t have properties other than their value. In other words, anthropomorphizing a little, int
variables don’t know anything about themselves. This chapter considers solutions to this problem given this observation.
Motivation
As you know from Chapter 3 on digit manipulation, in order to drop or extract digits from the left side of an integer, you needed to know the number of digits in the number. In the examples in that chapter, the number of digits was known. Unfortunately, that isn’t always the case. For example, credit card account numbers might have between six and nine digits. The problem, then, is that of determining the number of digits in a number.
Review
As you also know from Chapter 3 on digit manipulation, the position of a digit corresponds to a particular power of 10. Specifically, the digit in position [latex]n[/latex] (counting from the right, starting with 0) corresponds to the [latex]10^n[/latex]s place. For example, position [latex]2[/latex] corresponds to the [latex]10^2[/latex] or [latex]100[/latex]s place. To count digits you need to be able to invert the process. For example, to count a three-digit number, you need to find the position that the [latex]100[/latex]s place corresponds to.
As you hopefully recall, this is the domain of the logarithm. In a decimal (i.e., base 10) representation, the [latex]\log_{10}(x)[/latex] is often described as the value of [latex]n[/latex] that [latex]10[/latex] must be raised to in order to get [latex]x[/latex]. More formally, [latex]\log_{10}(x)[/latex] is the value of [latex]n[/latex] that satisfies [latex]x = 10^n[/latex]. So, returning to our example, the position of the [latex]100[/latex]s place corresponds to [latex]\log_{10}(100)[/latex], which is [latex]2[/latex] (since [latex]10^2[/latex] is [latex]100[/latex]). More generally, [latex]\log_{b}(x)[/latex] is the value of [latex]n[/latex] that satisfies [latex]x = b^n[/latex], where [latex]b[/latex] is referred to as the base (or radix) of the logarithm.
Thinking About The Problem
Evaluating [latex]\log_{10}(x)[/latex] can be quite difficult, in general. However, it is easy to find bounds. For example, since [latex]\log_{10}(100)[/latex] is [latex]2[/latex] and [latex]\log_{10}(1000)[/latex] is [latex]3[/latex] (and logarithms are monotonic) it follows that [latex]\log_{10}(x)[/latex] is in the interval [latex][2, 3)[/latex] for any [latex]x \in [100, 1000)[/latex]. This means that the [latex]\log_{10}[/latex] of any three-digit number is in [latex][2, 3)[/latex] and that the [latex]\log_{10}[/latex] of any four-digit number is in [latex][3, 4)[/latex]. For example:
Math.log10(7198)
evaluates to approximately3.8572118423168926
which, as expected, is in the interval [latex][3, 4)[/latex].Math.log10(462)
evaluates to approximately2.6646419755561257
which, as expected, is in the interval [latex][2,