【枕边算法】回文算法题PHP实现

①选择任一数值;

②翻转此数值(例如,选择13则翻转为31),并将原数值和翻转数值相加(13+31);

③相加结果若不是回文,则返回②反复执行,若是回文则终止算法

举例:

13+31=44,44是回文,退出

19+91=110,110+011=121,121是回文,退出


https://github.com/zhangyue0503/php/blob/master/%E6%9E%95%E8%BE%B9%E7%AE%97%E6%B3%95/1.7.php






$num = 197;

//13=44

//12=33

//14=55

//19=110

//125=646

//87=4884

//196=内存溢出

//197=881188

//找回文数字算法

function huiwenshuzi($num){

if($num>0){

//反过来

$reNum = (int)implode('',array_reverse(str_split($num)));

$newNum = $num+$reNum;

if(isHuiWen($newNum)){ //出口

return $num+$reNum;

}else{

return huiwenshuzi($newNum); //递归

}

}else{

return '错误';

}

}

//判断是否回文

function isHuiWen($str){

$str = preg_split('/(?

if (count($str) < 2) {

return false;

} else {

$isHui = true;

for ($i = 0; $i < count($str); $i++) {

if ($str[$i] != $str[count($str) - $i - 1]) {

$isHui = false;

break;

}

}

return $isHui;

}

}

echo huiwenshuzi($num);

推荐阅读更多精彩内容