Example
Example 1:
Input: "42"
Output: 42
Example 2:
Input: " -42"
Output: -42
Example 3:
Input: "4193 with words"
Output: 4193
Example 4:
Input: "words and 987"
Output: 0
Example 5:
Input: "-91283472332"
Output: -2147483648
时间复杂度: O(N)- 空间复杂度: O(1)
print_r(test(' 123fdfa'));
function test($str) {
$str = trim($str);
if (mb_strlen($str) == 0) {
return 0;
}
$position = true;
if ($str[0] == '+' || $str[0] == '-') {
if ($str[0] == '-') {
$position = false;
}
$str = substr($str,1,mb_strlen($str)-1);
} elseif ($str[0] < '0' || $str[0] > '9') {
return 0;
}
$rest = 0;
for ($i = 0; $i < mb_strlen($str); $i++) {
$char = $str[$i];
if ($char < '0' || $char > '9') {
break;
}
if ($char >= 0 || $char <= 9) {
$rest = $rest*10 + intval($char);
}
}
if ($position==false) {
$rest = 0-$rest;
}
return $rest;
}