自学内容网 自学内容网

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
}

原文地址:https://blog.csdn.net/weixin_66442839/article/details/143826971

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!