• 技术文章 >php教程 >PHP源码

    PHP实现逆波兰式 - 计算工资时用

    PHP中文网PHP中文网2016-05-25 17:13:08原创381
    php代码

    <?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核实处理。
    上一篇:Yii的smarty插件 ESmartyViewRenderer 中的错误更正 下一篇:PHP实现无限级分类(不使用递归)

    相关文章推荐

    • PHP禁止图片文件的被盗链函数• 使用simple_html_dom抓取oschina的新闻资讯• 解决json_encode 函数中文被编码成 null的办法• php学习笔记之面向对象编程• php中常用的函数集合

    全部评论我要评论

  • 取消发布评论发送
  • 1/1

    PHP中文网