PHP计算表达式-栈
生活随笔
收集整理的這篇文章主要介紹了
PHP计算表达式-栈
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
<?php
/*** 計算表達式思路* 1+2*3-2* 思路:* 1、掃描每個字符* 2、判斷是否運算符和數字* 3、數字直接進棧* 4、運算符* 1、第一個運算符直接入棧* 2、N個運算符要與之前運算符比較* 1、如果當前運算符大于棧頂的運算符* 1、從數棧取出兩個數字進行運算,其實這個就是優先級運算* 2、把結果入棧* 2、如果不大于直接入棧* 5、得到平級運算表達式* 6、遍歷運算符出棧進行運算,然后在入棧,一直到運算符為空。* @author wangdk**/
class Expression
{public $numArray = array();public $operArray = array();/*** 判斷是否為數字*/public function isNumeric($str) {return is_numeric($str);}/*** 判斷是否為運算符*/public function isOperation($str) {if ($str == '+' || $str == '-') {return 1;}if ($str == '*' || $str == '/') {return 2;}return 0;}/*** 根據運算符進行運算*/public function calc($ch, $numA, $numB) {$result = 0;switch($ch) {case '+':$result = $numA + $numB;break;case '-':$result = $numB - $numA;break;case '*':$result = $numA * $numB;break;case '/':$result = $numB / $numA;break;}return $result;}/*** 掃描表達式進行入棧*/public function getResult($str) {$count = strlen($str);for ($i = 0; $i < $count; $i++) {// 數字直接入棧if ($this->isNumeric($str[$i])) {array_push($this->numArray, $str[$i]);} else {// 第一個運算符直接入棧if (empty($this->operArray)) {$this->operArray[] = $str[$i];} else {// 多個運算符開始比較,去掉優先級$operArrayCopy = $this->operArray;$prev_operation = array_pop($operArrayCopy);// 如果當前運算符號小于 上一個運算符if ($this->isOperation($str[$i]) <= $this->isOperation($prev_operation)) {// 運算$prev_operation = array_pop($this->operArray);$first_num = array_pop($this->numArray);$second_num = array_pop($this->numArray);$result = $this->calc($prev_operation, $first_num, $second_num);$this->numArray[] = $result;array_push($this->operArray, $str[$i]);} else {array_push($this->operArray, $str[$i]);}}}}// 遍歷平級運算符,進行運算$operArrayCount = count($this->operArray);while($operArrayCount) {$prev_operation = array_pop($this->operArray);$first_num = array_pop($this->numArray);$second_num = array_pop($this->numArray);$result = $this->calc($prev_operation, $first_num, $second_num);$this->numArray[] = $result;$operArrayCount = count($this->operArray);}}}$e = new Expression();
$e->getResult('1+2*3+4*8');
echo '<pre>';
print_r($e->numArray);
print_r($e->operArray)
?>
轉載于:https://my.oschina.net/wangdk/blog/158787
總結
以上是生活随笔為你收集整理的PHP计算表达式-栈的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Cython安装
- 下一篇: 安装JDK 1.7时could not