-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSolution.php
47 lines (43 loc) · 1.02 KB
/
Solution.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<?php
// https://leetcode.com/problems/reverse-integer/
class Solution
{
/**
* @param Integer $x
* @return Integer
*/
function reverse($x)
{
$str = (string)$x;
$str = str_split($str);
$res = '';
for ($i = count($str) - 1; $i > -1; $i--) {
if ($str[$i] != "-") {
$res .= $str[$i];
}
}
while ($res[0] == "0") {
$res = substr($res, 1, strlen($res));
}
if (!$this->is_32bit_signed_int($res)) {
return 0;
}
if ($str[0] == "-") {
return (int)-$res;
}
return (int)$res;
}
function is_32bit_signed_int($value)
{
$options = ['min_range' => -2147483647, 'max_range' => 2147483647];
return false !== filter_var($value, FILTER_VALIDATE_INT, compact('options'));
}
}
$x = 123; //321
// $x = -123; //-321
$x = 120; //21;
// $x=1534236469; //0
// $x=-10;
$obj = new Solution();
$res = $obj->reverse($x);
var_dump($res);