There is such a question. Given a number string A, you need to determine whether A is a continuous multiplication number string. The definition of a continuous multiplication number string is that a number string can be split into several numbers. The following numbers (from the Nth starting with a number) is the product of the previous 2 numbers. This article mainly introduces you to an example of how to use PHP to determine whether it is a continuous multiplication of a number string. The article introduces it in detail through the example code, which has a certain reference and learning value for everyone. Friends who need it can follow the editor to learn together.
(1) '122' --- can be split into [1|2|2]
Result: 1×2=2 (multiply the number string)
(2) '1122242' --- can be split into [11|22|242]
Result: 11×22=242 (multiply the number string)
(3) '1224832256' --- can be split into [1|2|2|4|8|32|256]
Result: 1×2=2, 2×2=4, 2×4=8, 4×8=32, 8×32=256 (multiply the number string)
(4) '234547898185239692' --- can be split into [23454|7898|185239692]
Result: 23454×7898=185239692 (multiply the number string)
(5) '113' can be split into [1| 1|3]
Result: 1×1 != 3 (non-consecutive multiplication of numeric strings)
Code
/** * 判断是否连乘数字串函数 * @param $strNum * @return bool **/ function isExec($strNum) { $str = (string)$strNum; for ($i = 0; $i < strlen($str); $i++) { $k = 1; for ($j = $i + 1; $j < strlen($str); $j++) { $a_i = 0; $b_i = $i + 1; $p_i = $i + 1; $m_i = $k++; $c_i = $b_i + $m_i; $res = false; $formula = []; while (1) { $a = substr($str, $a_i, $p_i); $b = substr($str, $b_i, $m_i); $n = $a * $b; $c = substr($str, $c_i, strlen($n)); //echo '<br/>' . $a . '*' . $b . '=' . $n . '->' . $c . '<br/>'; if($c){ $formula[] = $a . '*' . $b . '=' . $n; } if ($c === false || $c === "") { break; } if (intval($n) == intval($c)) { $p_i = strlen($b); $m_i = strlen($n); $a_i = $b_i; $b_i = $c_i; $c_i = $b_i + $m_i; $res = true; } else { $res = false; break; } } if ($res === true) { print_r($formula); return true; } //var_dump($res) . '<br/>'; } } return false; }
Execution
var_dump(isExec('1224832256'));
//运行结果 Array [ [0] => 1*2=2 [1] => 2*2=4 [2] => 2*4=8 [3] => 4*8=32 [4] => 8*32=256 ] bool(true)
var_dump(isExec('234547898185239692'));
//运行结果 Array [ [0] => 23454*7898=185239692 ] bool(true)
var_dump(isExec('1122242') );
//运行结果 Array [ [0] => 11*22=242 ] bool(true)
var_dump(isExec('11234'));
//运行结果 bool(false)
Related recommendations:
Use PHP code to verify a string Is the number connected into a string of numbers?
The above is the detailed content of How to determine whether a string of numbers is multiplied consecutively in PHP. For more information, please follow other related articles on the PHP Chinese website!