LeetCode 题解工作台

找出最大的 N 位 K 回文数

给你两个 正整数 n 和 k 。 如果整数 x 满足以下全部条件,则该整数是一个 k 回文数 : x 是一个 回文数 。 x 可以被 k 整除。 以字符串形式返回 最大的 n 位 k 回文数 。 注意 ,该整数 不 含前导零。 示例 1: 输入: n = 3, k = 5 输出: "595" 解释:…

category

5

题型

code_blocks

0

代码语言

hub

3

相关题

当前训练重点

困难 · 状态·转移·动态规划

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你两个 正整数 nk

如果整数 x 满足以下全部条件,则该整数是一个 k 回文数

  • x 是一个 回文数
  • x 可以被 k 整除。

以字符串形式返回 最大的  nk 回文数

注意,该整数 含前导零。

 

示例 1:

输入: n = 3, k = 5

输出: "595"

解释:

595 是最大的 3 位 k 回文数。

示例 2:

输入: n = 1, k = 4

输出: "8"

解释:

1 位 k 回文数只有 4 和 8。

示例 3:

输入: n = 5, k = 6

输出: "89898"

 

提示:

  • 1 <= n <= 105
  • 1 <= k <= 9
lightbulb

解题思路

方法一

1
2

speed

复杂度分析

指标
时间and space complexity depend on n and k. With remainder tracking and DP, time is O(n * k) and space is O(n * k) in the worst case. Simple brute force is infeasible due to large n, highlighting the need for state transition optimization.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Check if you can construct the palindrome from halves rather than brute force.

  • question_mark

    Watch for handling the modulo of partially built numbers.

  • question_mark

    Consider state transitions to prune invalid prefixes efficiently.

warning

常见陷阱

外企场景
  • error

    Failing to account for leading zeros when building palindromes.

  • error

    Recalculating full numbers instead of using remainder DP, causing TLE.

  • error

    Ignoring symmetric digit placement leading to non-palindromic candidates.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Find the smallest n-digit palindrome divisible by k.

  • arrow_right_alt

    Return all n-digit palindromes divisible by k.

  • arrow_right_alt

    Determine the largest palindrome divisible by k within a range of n values.

help

常见问题

外企场景

找出最大的 N 位 K 回文数题解:状态·转移·动态规划 | LeetCode #3260 困难