1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// @Title: 寻找最近的回文数 (Find the Closest Palindrome)
// @Author: 15816537946@163.com
// @Date: 2022-03-24 00:04:41
// @Runtime: 0 ms
// @Memory: 1.9 MB
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
}