每周一道算法题001:回文数

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了每周一道算法题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)
}

脚本宝典总结

以上是脚本宝典为你收集整理的每周一道算法题001:回文数全部内容,希望文章能够帮你解决每周一道算法题001:回文数所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。