列表

详情


564. 寻找最近的回文数

给定一个表示整数的字符串 n ,返回与它最近的回文整数(不包括自身)。如果不止一个,返回较小的那个。

“最近的”定义为两个整数差的绝对值最小。

 

示例 1:

输入: n = "123"
输出: "121"

示例 2:

输入: n = "1"
输出: "0"
解释: 0 和 2是最近的回文,但我们返回最小的,也就是 0。

 

提示:

原站题解

去查看

上次编辑到这里,代码来自缓存 点击恢复默认模板
class Solution { public: string nearestPalindromic(string n) { } };

python3 解法, 执行用时: 40 ms, 内存消耗: 16.1 MB, 提交时间: 2023-05-14 19:43:54

class Solution:
    def nearestPalindromic(self, n: str) -> str:
        length, int_n = len(n), int(n)
        if int_n < 10 or int_n == 10 ** (length-1): return str(int_n-1)
        if int_n - 1 == 10 ** (length-1): return str(int_n-2)
        if int_n + 1 == 10 ** length: return str(int_n + 2)

        pre = int(n[:(length+1)//2])
        tmp = [s[:length//2] + s[::-1] for s in [str(pre + dx) for dx in (-1, 0, 1)]]
        return min(tmp, key=lambda x: (x==n, abs(int(x)-int_n)))

javascript 解法, 执行用时: 52 ms, 内存消耗: 42.3 MB, 提交时间: 2023-05-14 19:43:07

/**
 * @param {string} n
 * @return {string}
 */
var nearestPalindromic = function(n) {
    getBigInt = function(orignal, v) {
        for(;orignal > 0; orignal /= 10n)
            v = 10n * v + orignal % 10n
        return v
    }

    const len = n.length, nVal = BigInt(n)
    if(len == 1)
        return nVal - 1n + ''
    const half = BigInt(n.substr(0, (len + 1) >> 1)), ans = new Set()
    ans.add(BigInt(Math.pow(10, len - 1)) - 1n)
    ans.add(BigInt(Math.pow(10, len)) + 1n)
    if(len & 1 == 1) {
        ans.add(getBigInt((half+1n)/10n, half + 1n))
        ans.add(getBigInt(half/10n, half))
        ans.add(getBigInt((half-1n)/10n, half - 1n))
    } else {
        ans.add(getBigInt(half + 1n, half + 1n))
        ans.add(getBigInt(half, half))
        ans.add(getBigInt(half - 1n, half - 1n))
    }
    let res = -1
    for(const other of ans) {
        if(other != nVal) {
            if(res == -1)
                res = other
            let o = other - nVal, r = res - nVal
            if(o < 0)
                o *= -1n
            if(r < 0)
                r *= -1n
            if(o < r || (other < res && o == r))
                res = other
        }
    }
    return res + ''
};

python3 解法, 执行用时: 36 ms, 内存消耗: 16 MB, 提交时间: 2023-05-14 19:42:42

class Solution:
    def nearestPalindromic(self, n: str) -> str:
        if len(n) == 1:
            return str(int(n) - 1)
        l = len(n)
        half, v, ov = n[:l//2], int(n[:(l+1)//2]), int(n)
        res = set()
        s1, s2 = str(v-1), str(v + 1)
        res.add("9" * (l - 1))
        res.add("1" + "0" * (l - 1) + "1")
        if l % 2:
            res.add(s1[:-1] + s1[-1] + s1[:-1][::-1])
            res.add(s2[:-1] + s2[-1] + s2[:-1][::-1])
        else:
            res.add(s1 + s1[::-1])
            res.add(s2 + s2[::-1])
        if n[::-1] != n:
            res.add(half + n[l//2] + half[::-1] if l % 2 else half + half[::-1])
        if n in res:
            res.remove(n)
        return min(res, key = lambda x:(abs((k:=int(x)) - ov), k))

golang 解法, 执行用时: 4 ms, 内存消耗: 1.9 MB, 提交时间: 2023-05-14 19:42:09

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
}

python3 解法, 执行用时: 56 ms, 内存消耗: 16.1 MB, 提交时间: 2023-05-14 19:41:56

class Solution:
    def nearestPalindromic(self, n: str) -> str:
        m = len(n)
        candidates = [10 ** (m - 1) - 1, 10 ** m + 1]
        selfPrefix = int(n[:(m + 1) // 2])
        for x in range(selfPrefix - 1, selfPrefix + 2):
            y = x if m % 2 == 0 else x // 10
            while y:
                x = x * 10 + y % 10
                y //= 10
            candidates.append(x)

        ans = -1
        selfNumber = int(n)
        for candidate in candidates:
            if candidate != selfNumber:
                if ans == -1 or \
                        abs(candidate - selfNumber) < abs(ans - selfNumber) or \
                        abs(candidate - selfNumber) == abs(ans - selfNumber) and candidate < ans:
                    ans = candidate
        return str(ans)

上一题