Home  >  Article  >  php教程  >  PHP实现逆波兰式 - 计算工资时用

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

PHP中文网
PHP中文网Original
2016-05-25 17:13:08963browse

php代码

 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*/
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn