I have problem with one problem on HackersRank – Day 16: Exceptions – String to Integer . In short task is
Read a string, SS, and print its integer value; if SS cannot be converted to an integer, print Bad StringBad String.
Note: You must use the String-to-Integer and exception handling constructs built into your submission language. If you attempt to use loops/conditional statements, you will get a 00 score.
Task itself is quite simple and I solved it on Python. My problem is fact that I don’t see the way to do that with PHP – is there function in PHP that throws Exception if you are trying to convert string to integer?
Advertisement
Answer
And here’s another hacky solution using the try {..} catch mechanism:
try { new ReflectionClass('ReflectionClass' . ((int)$SS . "" !== $SS)); echo $SS; } catch (Exception $e) { echo "Bad StringBad String"; }
It works like this: if the string $SS
doesn’t actually resolve to an integer, the code will try to lookup the ReflectionClass1 class, which, in the end, will throw a ReflectionException
.
The parsing works by simply casting $SS
to int
and then back to string and comparing it to the initial value.