2024 FALL CMPINF 401 Xtra credit: #2 HORNER's METHOD


Execute your program like this: $ java Horner 31459   (negative numbers are allowed)

The output of the above execution whould be nothing but one single int whose value is 314159

Background

We have used the .nextInt() call in the Scanner class and the Integer.parseInt() method many times. Both of these functions do the following: The accept a String and convert it to a number. Both of these algorithms use Horner's method of evaluating a polynomial. Any decimal number is a polynominal.

31459 is 3x10^4 + 1x10^3 + 4x10^2 + 5*10^1 +9x10^0. This is a polynomial on base 10.

The algorithm goes like this: for each number in the polynomial starting at .charAt(0) upto including charAt( s.length()-1) (OR BACKWARDS IF YOU LIKE) look at each digit and covert that digit to it's decimal value. Suppose you have char ch='5'; to convert to the int 5 you just do: int number = ch - '0'; In Java you are allowed to add and subtract a char to/from a char. This works becuase the ascii value of the digit chars increase by 1 from 0 to 9. The numberic/ascii value of '5' is not 5 it's 53. The ascii value of '0' is not 0, it's 48. So if you do '5' - '0' you are really doing 53 - 48 = 5.

Now back to the algorithm: for each digit that you convert to its numberic digit value i.e. '5' => 5, you must weight that digit by its power of 10 and add it to a running total. When you are all done you have the value of the String converted to an int.