Reprint: http://www.lamper.cn/html/2007/03-21/61.html
1, using PHP to describe the data conversion
The conversion of decimal N and other D-ary numbers is the basic problem of computing implementation, and there are many solutions, one of the simple algorithms is based on the following principles:
n= (N div d) *d+n mod D (where div is divisible operation, mod for remainder operations)
<?php
function convert ($num)
{
$stack = Array ();
while ($num) {
Array_push ($stack, $num%8);
$num = Floor ($num/8);
}
while ($stack) {
echo Array_pop ($stack);
}
}
?>
Test instance:
<?php
CONVERT (1348);
?>
2, brackets matching the test
Suppose an expression allows you to include two types of parentheses: parentheses and brackets, which are nested in a random order, that is, [] () or [()] as the correct format. But [(]) or [()] or (()] are not in the correct format.
The algorithm used in PHP to verify the validity of the expression bracket reference is as follows:
<?php
$str is an expression
function Check ($STR)
{
$stack = Array ();
$strLength = strlen ($STR);
for ($i =0; $i < $strLength; $i + +) {
Switch ($str [$i]) {
Case "(":
Array_push ($stack, $str [$i]);
Break
Case "[":
Array_push ($stack, $str [$i]);
Break
Case ")":
if (count ($stack) && array_pop ($stack) = = "(") break;
else return false;
Case "]":
if (count ($stack) && array_pop ($stack) = = "[") break;
else return false;
}
}
if (count ($stack) >0) return false;
else return true;
}
?>
Test instance:
<?php
$str = "LK (asdf) []";
Var_dump (check ($STR));
?>