[Home] [Puzzles & Projects] [Delphi Techniques] [Math topics] [Library] [Utilities]


Problem DescriptionHow many times does the digit 1 appear in all of the integers from 0 though
999,999? Background & TechniquesI wrote this program to verify the answer I had obtained using pencil and paper. My manual analysis turned out to be wrong. I had figured that the units position 0 to 9 cycle would occur 100,000 times contributing one "1" each time for 100,000 ones. Plus there are 10,000 09 cycles of the 10's position, adding 10,000 more ones, plus 1000 cycles in the hundreds positions adding 1,000 more, etc. for a total of 111,111 ones between 0 and 999,999. Wrong! I'll leave it to the reader to figure what was wrong with my logic either before or after seeing the answer provided by the program. I figured it out after, which made writing the program worthwhile. Since only has a few lines of code to do the work of counting, I decided it would be worth posting the program in the "Beginners" category for budding Delphi programmers. Programmer's Notes:TRadiogroup, Calcmethod, selects one of 2 methods to count occurrences of the specified digit with each click of the Searchbtn button. TSpinedit controls are used to select digit to be tested (Spinedit1.value) and the range on integers over which to test (Spinedit2.value and Spinedit2.value). A loop over the range to be tested performs the test on each integer using whichever method was selected. When the loop is complete, a format statement displays the results in a TMemo, Memo2. For a given integer N, "Method 1" uses the modulus ("mod") function as "N mod 10" to get the units position digit to test and then uses the integer divide function ("div") to as in "N div 10" in a loop to shift N one digit to the right to test the next digit. Here is the essential part of the loop for testing an integer N:
"Method 2" uses the integer to string ("Inttostr") function to convert each number, I, to be tested to a string value and then compares each character of the string against a character version of the digit being counted. The code to obtain a character version of the digit to be counted, Spinedit1.value, uses typecasting to add Spinedit1.value to the ordinal value of the character zero, and treats the sum as a character Sdigit. Here is the code:
That's about it. Running/Exploring the ProgramSuggestions for Further Explorations

[Feedback] [Newsletters (subscribe/view)] [About me]Copyright © 20002017, Gary Darby All rights reserved. 