百度谷歌搜索無果,之好自己造一次輪子。
function rpn2html' target='_blank'>value($str){ $arr = explode(',',$str); $stack = array(); $len = count($arr); for($i=0;$i<$len;$i++){ if(is_numeric($arr[$i])){ array_push($stack,$arr[$i]); }else{ $op = $arr[$i]; $right = array_pop($stack); $left = array_pop($stack); eval("/$re = $left $op $right;"); array_push($stack,$re); } } return $stack[0];}
使用方法:
$str = "1,2,3,+,*,4,-,5,+,7,*";echo rpn2value($str);
另附中序轉后序代碼,版權歸原作者所有
/** * math_rpn * * 實現逆波蘭式算法 * * @author sparkHuang [email protected] * @version RPN 1.0.0 * */class math_rpn { //初始的計算表達式 private $_expression = ''; //處理后的逆波蘭表達式 private $_rpnexp = array(); //模擬棧結構的數組 www.it165.net private $_stack = array('#'); //正則判斷 //private $_reg = '/^([A-Za-z0-9/(/)/+/-/*//])*$/'; //優先級 private $_priority = array('#' => 0, '(' => 10, '+' => 20, '-' => 20, '*' => 30, '/' => 30); //四則運算 private $_operator = array('(', '+', '-', '*', '/', ')'); public function __construct($expression) { $this->_init($expression); } private function _init($expression) { $this->_expression = $expression; } public function exp2rpn() { $len = strlen($this->_expression); for($i = 0; $i < $len; $i++) { $char = substr($this->_expression, $i, 1); if ($char == '(') { $this->_stack[] = $char; continue; } else if ( ! in_array($char, $this->_operator)) { $this->_rpnexp[] = $char; continue; } else if ($char == ')') { for($j = count($this->_stack); $j >= 0; $j--) { $tmp = array_pop($this->_stack); if ($tmp == "(") { break; } else { $this->_rpnexp[] = $tmp; } } continue; } else if ($this->_priority[$char] <= $this->_priority[end($this->_stack)]) { $this->_rpnexp[] = array_pop($this->_stack); $this->_stack[] = $char; continue; } else { $this->_stack[] = $char; continue; } } for($i = count($this->_stack); $i >= 0; $i--) { if (end($this->_stack) == '#') break; $this->_rpnexp[] = array_pop($this->_stack); } return $this->_rpnexp; }}//測試實例$expression = "(A*(B+C)-E+F)*G";var_dump($expression);$mathrpn = new math_rpn($expression);var_dump($mathrpn->exp2rpn());PHP編程
鄭重聲明:本文版權歸原作者所有,轉載文章僅為傳播更多信息之目的,如作者信息標記有誤,請第一時間聯系我們修改或刪除,多謝。
新聞熱點
疑難解答