①選擇任一數值;
②翻轉此數值(例如,選擇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);
閱讀更多 ZyBlog 的文章