This article mainly introduces an example of how to use PHP to determine whether it is a continuous multiplication of a string of numbers. The article introduces it in detail through the example code, which has certain reference and learning value for everyone. Friends who need it will follow the editor. Study and study.
Description
There is such a question. Given a number string A, you need to determine whether A is a consecutive multiplication of numbers. The definition of a string is that a string of numbers can be split into several numbers, and the following number (starting from the Nth number) is the product of the previous two numbers.
Example
(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 number 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)
//运行结果 Array [ [0] => 11*22=242 ] bool(true)
//运行结果 bool(false)
Related recommendations:
PHP implements Excel long number string is displayed as scientific notation code Share
The above is the detailed content of PHP implements a method to determine whether a string of numbers is multiplied consecutively. For more information, please follow other related articles on the PHP Chinese website!