Parse 32-bit Integer
PHP
Hard
6 views
Problem Description
Given an integer as text, print it if it fits 32-bit signed, else print OVERFLOW.
Input Format
One token s.
Output Format
Integer or OVERFLOW.
Official Solution
<?php
$inputText=trim(stream_get_contents(STDIN));
if($inputText==='') exit;
if(!preg_match('/^[+-]?[0-9]+$/',$inputText)){ echo 'OVERFLOW'; exit; }
$neg=false;
if($inputText[0]==='-'){ $neg=true; $inputText=substr($inputText,1); }
elseif($inputText[0]==='+') $inputText=substr($inputText,1);
$inputText=ltrim($inputText,'0'); if($inputText==='') $inputText='0';
$limit=$neg ? '2147483648' : '2147483647';
if(strlen($inputText)<strlen($limit) || (strlen($inputText)===strlen($limit) && $inputText<=$limit)){
$val=intval(($neg?'-':'').$inputText);
echo strval($val);
}else echo 'OVERFLOW';
?>
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!