StringToInteger   A
last analyzed

Complexity

Total Complexity 13

Size/Duplication

Total Lines 25
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 13
eloc 16
c 2
b 0
f 0
dl 0
loc 25
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
C myAtoi() 0 23 13
1
<?php
2
3
declare(strict_types=1);
4
5
namespace leetcode;
6
7
class StringToInteger
8
{
9
    public static function myAtoi(string $s): int
10
    {
11
        $s = trim($s);
12
        $n = strlen($s);
13
        if ($n === 0) {
14
            return 0;
15
        }
16
        [$sign, $base, $i] = [1, 0, 0];
17
        while ($i < $n && $s[$i] === ' ') {
18
            $i++;
19
        }
20
        if ($i < $n && ($s[$i] === '+' || $s[$i] === '-')) {
21
            $sign = ($s[$i++] === '+') ? 1 : -1;
22
        }
23
        [$min, $max] = [-2 ** 31, 2 ** 31 - 1]; // -2147483648~2147483647
24
        while ($i < $n && is_numeric($s[$i])) {
25
            if ($base > $max || $base < $min) {
26
                return $sign === 1 ? $max : $min;
27
            }
28
            $base = 10 * $base + ($s[$i++] - '0');
29
        }
30
31
        return $base * $sign;
32
    }
33
}
34