繁体   English   中英

PHP:从给定的表达式中找到丢失的数字 x

[英]PHP: Find the missing digit x from the given expression

让函数MissingDigit (str)接受str参数,这将是一个简单的数学公式,包含三个数字、一个运算符(+、-、* 或 /)和一个等号 (=),并返回完成方程。 在等式中的一个数字中,会有一个 x 字符,您的程序应该确定缺少哪个数字。 例如,如果str“3x + 12 = 46” ,那么您的程序应该输出4。x字符可以出现在三个数字中的任何一个中,并且所有三个数字都将大于或等于 0 且小于或等于 1000000 .


function MissingDigit($str) {

   // code goes here
   return $str;
}
// keep this function call here
echo MissingDigit ("3x + 12 = 46");

?>```
function MissingDigit($str) {

$parts = explode('=',$str);
if (strpos($parts[1],'x') !== false) {
    $aux  = $parts[1];
    $parts[1] = $parts[0];
    $parts[0] = $aux;
}
$operands = preg_split('/(\+|\-|\*|\/)/', $parts[0]);

$detectSign = function($a) {
    $signs = ['+','-','/','*'];
    foreach ($signs as $s) {
        if (strpos($a,$s)){
            return $s;
        }
    }
    return;
};
$op = $operands[0];
$xoperand = $operands[1];
if (strpos($operands[0],'x') !== null ) {
    $op = $operands[1];
    $xoperand = $operands[0];
}
$sign = $detectSign($parts[0]);

$opozite = ['+'=>'-','-'=>'+','/'=>'*','*'=>'/'];

$result = eval('return '.$parts[1].(string)$opozite[$sign].(string)$op.';');
return str_replace(str_split(strtolower($xoperand)), '', strtolower($result)); 

}

我从这里得到了正确的解决方案。

有从第一个操作数、第二个操作数甚至结果中获取x值的解决方案,

例子:

Input: S = “4x + 16 = 60”
Output: 4

Input: S = “8 - 5 = x”
Output: 3

Input: S = “40 - 2x = 19”
Output: 1

我在谷歌上搜索了很多次,我看到了很多代码,但我在PHP Guru中找到了最佳解决方案

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM