Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP String-to-Integer Exception

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?

like image 803
CrazyCrow Avatar asked Nov 28 '22 04:11

CrazyCrow


1 Answers

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.

like image 66
Razvan Avatar answered Dec 10 '22 22:12

Razvan