https://www.nowcoder.com/ta/huawei? ?HJ50
输入:
(56-2)/(4+2)
1+2+3+4
3+2*{1+2*[-4/(8-6)+7]}
* index.php
<?php
include "Scanner.php";
include "HJ50.php";
class Solution {
public static function main() {
$sc = new Scanner("php://stdin");
// $sc = new Scanner("./input/input.txt");
$solution = new HJ50();
while ($sc->hasNext()) {
$line = $sc->nextLine();
printf("%s\n", $solution->compute($line));
}
}
}
Solution::main();
* Scanner.php
* HJ50.php
<?php
class HJ50
{
const ORD_0 = 48;
private static function isdigit($c): bool {
$code = ord($c[0]);
return 48 <= $code && $code < 58;
}
private static function isOpenBrace($c) :bool {
return $c == '{' || $c == '[' || $c == '(';
}
private static function isCloseBrace($c) : bool {
return $c == '}' || $c == ']' || $c == ')';
}
/**
* @param $data string
* @param $len int
* @param $pos int
* @return int
*/
private static function _compute(string $data, int $len, int &$pos): int
{
$num = 0;
$op = '+';
$st = array(); // stack
while ($pos < $len) {
if (self::isOpenBrace($data[$pos])) {
$pos += 1;
$num = self::_compute($data, $len, $pos);
}
while ($pos < $len && self::isdigit($data[$pos])) {
$num = $num * 10 + ord($data[$pos]) - self::ORD_0;
$pos += 1;
}
switch ($op) {
case '+': array_push($st, $num); break;
case '-': array_push($st, -$num); break;
case '*':
$tmp = array_pop($st);
$tmp *= $num;
array_push($st, $tmp);
break;
case '/':
$tmp = array_pop($st);
$tmp = floor($tmp / $num);
array_push($st, $tmp);
break;
default:
}
$num = 0;
$op = $data[$pos];
if (self::isCloseBrace($data[$pos])) {
$pos += 1;
break;
}
$pos += 1;
}
$sum = 0;
while (!empty($st)) {
$sum += array_pop($st);
}
return $sum;
}
/**
* @param $data
* @return int
*/
public function compute($data): int
{
$pos = 0;
return self::_compute($data, strlen($data), $pos);
}
}
|