MCS-177 Extra Credit 1: Integers and Strings

Start: Tuesday, 3/4; Due: Friday, 3/14, by the beginning of class

You are to work on this individually.

Overview

Integer and string objects are different even though they may look very similar. 1234 is an integer representing one thousand, two hundred, thirty four while "1234" is a string representing the characters '1', '2', '3' and '4'. It is possible to use the procedures int and str to convert between integers and strings.

   > str(123)
    '123'
   > int('-5412')
    -5412
While these procedures exist, we can write our own procedures that provide the same functionality. Write the contract and implementation of the procedures strToInt that takes a string that contains digits and returns an integer representation of the string. Therefore, strToInt is equivalent to int.

   > strToInt('31415')
    31415
   > strToInt('-7')
    -7
   > strToInt('+2358')
    2358

You may assume that only valid strings are used with the procedure. For example, no one will attempt to run strToInt('abc').

Restriction

  1. You may not use if to distinguish digits. However, you may use if to distinguish positive and negative integers.
  2. You only use the concepts learned in chapters 1-3.
  3. You may not use the built-in procedure int.
  4. You must work on this extra credit individually.

Hints

  1. You may find the procedure ord useful in the implementation (see textbook page 92-93).

Submitting your work

You will be submitting your code using Moodle; click on the following link for instructions on submitting code using Moodle.

Grading

You will earn one point for each of the following accomplishments towards an in-class exercise:

  1. You wrote a correct contract for strToInt.
  2. strToInt converts a string of digits to an integer correctly.
  3. strToInt also converts strings starting with a + or - sign correctly.
  4. Your implementation is not unnecessarily complex.