Skip to content

Instantly share code, notes, and snippets.

@marick
Last active August 12, 2017 00:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marick/f334dccb968a0b93144428dcf54e1f3f to your computer and use it in GitHub Desktop.
Save marick/f334dccb968a0b93144428dcf54e1f3f to your computer and use it in GitHub Desktop.
-- To make things interesting, I decided to assume a 32-bit machine.
-- Because invalid 32-bit numbers don't lie on nice boundaries, you
-- have to be careful about doing validity checks before multiplying.
-- That is, you can't calculate out a value of 2147483648 and then
-- check if that's bigger than the 32-bit boundary (2147483647) because
-- on a 32-bit machine, the value you'd be checking would be way negative.
toInt "1" => 1
toInt "-1" => -1
-- strings with too many characters are rejected (but there's more to the story)
toInt "1000000000" => 1000000000 ## must fit within 2^32
toInt "10000000000" => error ## definitely does not fit
-- There are positive boundaries
toInt "2147483647" => 2147483647
toInt "2147483648" => error
-- negative boundaries
toInt "-2147483648" => -2147483648 ## one more valid negative than positive number
toInt "-2147483649" => error
-- can add an explicit plus sign (note this would screw up a naive length check)
toInt "+2147483647" => 2147483647
toInt "" -> error
toInt "-" -> error
toInt "+" -> error
toInt "--5" -> error
toInt "5a" -> error
toInt "a6" -> error
toInt " 6" -> error
toInt "6 " -> error
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment