php判断一个数是否是回文数,每周一道算法题001:回文数

题目:

找出大于10的最小的2进制,8进制,10进制都是回文数的最小的数。回文数指的是正读和反读都是一样的数,例如:33,10001,123454321...

思路:

先转换进制,然后统一处理成字符串进行比较

解答:

PHP

function execute(){

$x = 11;

while (1) {

if ($x == strrev($x)

&& decbin($x) == strrev(decbin($x))

&& decoct($x) == strrev(decoct($x))) {

break;

}

$x += 2;

}

return $x;

}

$result = execute();

echo $result;

golang

package main

import (

"fmt"

"strconv"

)

func main() {

result := Execute()

fmt.Println(result)

}

func Execute() string {

xStr := ""

for x := 11; ; x += 2 {

xStr = strconv.Itoa(x)

xBin := strconv.FormatInt(int64(x), 2)

xOct := strconv.FormatInt(int64(x), 8)

if xStr == Reverse(xStr) && xBin == Reverse(xBin) && xOct == Reverse(xOct) {

break

}

}

return xStr

}

// 字符串翻转

func Reverse(s string) string {

runes := []rune(s)

for from, to := 0, len(runes)-1; from < to; from, to = from+1, to-1 {

runes[from], runes[to] = runes[to], runes[from]

}

return string(runes)

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值