- Forward


Digit Counting
A Programming Pattern


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu

Print

Motivation
Back SMYC Forward
  • The Context:
    • There are many situations in which a program needs to know the number of digits in an integer.
  • The Complication:
    • Numbers don’t "know anything" about themselves (i.e., don't have any attributes other than their value)
Review
Back SMYC Forward
  • Positional Representation:
    • The digit in position \(n\) (counting from the right, starting with 0) corresponds to the \(10^n\)s place
  • Reversing the Process:
    • To find the position of a particular place you need use a logarithm (recall that the \(\log_{10}(x)\) is the value of \(n\) that satisfies \(x = 10^n\))
Thinking About the Problem
Back SMYC Forward
  • Some Observations:
    • Evaluating the \(\log_{10}(x)\) can be difficult
    • Approximating it is easy
  • The Process:
    • Since \(log_{10}(100)\) is 2, \(log_{10}(1000)\) is 3, and logarithms are monotonic, it follows that \(log_{10}(x)\) is in the interval \([2,3)\) for any \(x \in [100, 1000)\)
Thinking About the Problem (cont.)
Back SMYC Forward
  • The Number 7198:
    • Math.log10(7198) is approximately 3.8572118423168926 which is in the interval \([3,4)\)
  • The Number 462:
    • Math.log10(462) is approximately 2.6646419755561257 which is in the interval \([2,3)\)
The Pattern
Back SMYC Forward
  • The Idea:
    • \(log_{10}()\) of any \(n\)-digit number will be in the interval \([n-1, n)\)
  • The Pattern:
    • javaexamples/programmingpatterns/DigitCounting.java (Fragment: pattern)
       
An Example
Back SMYC Forward
  • The Problem:
    • We need to convert a dollar amount (e.g., an income or a house price) into a phrase like "6 figures" or "7 figures"
  • A Specific Example:
    • A person who earns $156,720 per year has a (int)Math.log10(156720) + 1 (i.e., 6) figure salary
There's Always More to Learn
Back -