欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  php教程

百度面试题:解析字符串四则表达式

程序员文章站 2022-05-06 20:50:27
...
<?php
 
/**
 * @author yusaint
 * @copyright 2011
 */
function cal($expr)
{
    $splittedBy_multi = explode('*', $expr); // (12/3) (2) (12) (12/4)
    $temp = array();
    print_r($splittedBy_multi);
    foreach ($splittedBy_multi as $k => $v) {
 
        $splittedBy_divided = explode('/', $v);
        if (count($splittedBy_divided) > 1) {
            $temp[$k] = intval($splittedBy_divided[0]) * intval($splittedBy_divided[0]);
            foreach ($splittedBy_divided as $val) {
                $temp[$k] /= intval($val);
            }
        } else
            $temp[$k] = intval($v);
    }
    return array_product($temp);
 
 
}
$expr = "10-4+123+100*98*8/100*4*3+3-12/3/4*2*12*12/4+4-8+12/3*12+12";
$splittedBy_plus = explode('+', $expr); //0=>(4*3)  1=>(3-12/3/4*2*12*12/4) 2=>(4-8)
$temp = array();
foreach ($splittedBy_plus as $k => $v) {
    $splittedBy_minus = explode('-', $v); // 3 12/3/4*2*12*12/4
    if (count($splittedBy_minus) > 1) //(3) (12/3/4*2*12*12/4) (4) (8)
        {
        $temp_minus = array();
        foreach ($splittedBy_minus as $key => $value) {
            $temp_minus[$key] = cal($value);
        }
        $minus = 2 * $temp_minus[0];
        foreach ($temp_minus as $value) {
            $minus -= (int)$value;
        }
        $temp[$k] = $minus;
    } else {
        $temp[$k] = cal($v);
    }
 
 
}
$sum = 0;
foreach ($temp as $value) {
    $sum += $value;
}
echo 'the parsed value is:' . $sum."\n";
echo 'the original value is:'.(10-4+123+100*98*8/100*4*3+3-12/3/4*2*12*12/4+4-8+12/3*12+12);
?>
相关标签: php