每周一道算法题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)
}
标签:string,runes,strconv,算法,001,result,&&,xStr,回文 来源: https://blog.51cto.com/ustb80/2419235