Python Programming Exercises, Gently Explained
99
The function creates an integerNum variable to hold the integer form of stringNum as we
build it. This variable starts with the value 0. Your code must also note if there is a minus sign at the
start of the string, in which case
Our algorithm loops over the individual digits in the stringNum parameter, starting on the left
and moving right. The code multiplies current integer in integerNum by 10 to ―move‖ all of these
digits to the left by one place, then adds the current digit.
For example, if we needed to convert the string '41096' to an integer, the code needs to carry
out the following operations:
integerNum
= 0
integerNum
= (0 * 10) + 4 = 4
integerNum
= (4 * 10) + 1 = 41
integerNum
= (41 * 10) + 0 = 410
integerNum
= (410 * 10) + 9 = 4109
integerNum
= (4109 * 10) + 6 = 41096
Before returning, we convert this integer to a negative number if the original string began with a
minus sign.
Dostları ilə paylaş: