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.
While these procedures exist, we can write our own procedures that provide the same functionality. Write the contract and implementation of the procedures
> str(123)
'123'
> int('-5412')
-5412
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')
.
if
to distinguish digits. However, you may use if
to distinguish positive and negative integers.int
.
ord
useful in the implementation (see textbook page 92-93).
You will be submitting your code using Moodle; click on the following link for instructions on submitting code using Moodle.
You will earn one point for each of the following accomplishments towards an in-class exercise:
strToInt
.strToInt
converts a string of digits to an integer correctly.strToInt
also converts strings starting with a +
or -
sign correctly.