PHP实现逆波兰式 - 计算工资时用
May 25, 2016 pm 05:13 PMphp代码
<?php /** * math_rpn * * 实现逆波兰式算法 * * @author sparkHuang 260558820@qq.com * @version RPN 1.0.0 * */ class math_rpn { //初始的计算表达式 private $_expression = ''; //处理后的逆波兰表达式 private $_rpnexp = array(); //模拟栈结构的数组 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()); /*End of php*/
登入後複製
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱門文章
兩個點博物館:邦格荒地地點指南
4 週前
By 尊渡假赌尊渡假赌尊渡假赌
擊敗分裂小說需要多長時間?
3 週前
By DDD
倉庫:如何復興隊友
3 週前
By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒險:如何獲得巨型種子
3 週前
By 尊渡假赌尊渡假赌尊渡假赌
公眾號網頁更新緩存難題:如何避免版本更新後舊緩存影響用戶體驗?
3 週前
By 王林

熱門文章
兩個點博物館:邦格荒地地點指南
4 週前
By 尊渡假赌尊渡假赌尊渡假赌
擊敗分裂小說需要多長時間?
3 週前
By DDD
倉庫:如何復興隊友
3 週前
By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒險:如何獲得巨型種子
3 週前
By 尊渡假赌尊渡假赌尊渡假赌
公眾號網頁更新緩存難題:如何避免版本更新後舊緩存影響用戶體驗?
3 週前
By 王林

熱門文章標籤

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)