当前位置: 首页 > article >正文

Golang | Leetcode Golang题解之第564题寻找最近的回文数

题目:

题解:

func nearestPalindromic(n string) string {
    m := len(n)
    candidates := []int{int(math.Pow10(m-1)) - 1, int(math.Pow10(m)) + 1}
    selfPrefix, _ := strconv.Atoi(n[:(m+1)/2])
    for _, x := range []int{selfPrefix - 1, selfPrefix, selfPrefix + 1} {
        y := x
        if m&1 == 1 {
            y /= 10
        }
        for ; y > 0; y /= 10 {
            x = x*10 + y%10
        }
        candidates = append(candidates, x)
    }

    ans := -1
    selfNumber, _ := strconv.Atoi(n)
    for _, candidate := range candidates {
        if candidate != selfNumber {
            if ans == -1 ||
                abs(candidate-selfNumber) < abs(ans-selfNumber) ||
                abs(candidate-selfNumber) == abs(ans-selfNumber) && candidate < ans {
                ans = candidate
            }
        }
    }
    return strconv.Itoa(ans)
}

func abs(x int) int {
    if x < 0 {
        return -x
    }
    return x
}

http://www.kler.cn/a/402374.html

相关文章:

  • 如何使用ChatGPT写推荐信?
  • 阿里巴巴工程师最新版 1180 道 Java 面试题及答案整理
  • 【单片机硬件基础】CPU结构和功能
  • 将容器测试托管到Jenkins
  • PGSQL记录
  • 每天10个vue面试题(九)
  • odoo使用SSE
  • 高效Django随机查询优化方案
  • SpringFrameWork基于配置类方式管理Bean
  • go-zero(二) api语法和goctl应用
  • 同三维T80004EHU 高清HDMI/USB编码器
  • 从0开始机器学习--Day27--主成分分析方法
  • 孙玲:从流水线工人到谷歌程序员
  • Pycharm
  • 高效工具推荐:基于WebGPU的Whisper Web结合内网穿透远程使用指南
  • MySQL更换瀚高语法更换
  • reactflow 中 reactflowprovider 组件作用
  • 论文PDF页面无法下载PDF
  • react 中 useReducer Hook 作用
  • k8s篇之控制器类型以及各自的适用场景