LeetCode 题解工作台
旋转数字
我们称一个数 X 为好数, 如果它的每位数字逐个地被旋转 180 度后,我们仍可以得到一个有效的,且和 X 不同的数。要求每位数字都要被旋转。 如果一个数的每位数字被旋转以后仍然还是一个数字, 则这个数是有效的。0, 1, 和 8 被旋转后仍然是它们自己;2 和 5 可以互相旋转成对方(在这种情况下…
2
题型
5
代码语言
3
相关题
当前训练重点
中等 · 状态·转移·动态规划
答案摘要
一种直观且有效的思路是,直接枚举 中的每个数,判断其是否为好数,若为好数,则答案加一。 那么题目的重点转化为如何判断一个数字 是否为好数。判断的逻辑如下:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
我们称一个数 X 为好数, 如果它的每位数字逐个地被旋转 180 度后,我们仍可以得到一个有效的,且和 X 不同的数。要求每位数字都要被旋转。
如果一个数的每位数字被旋转以后仍然还是一个数字, 则这个数是有效的。0, 1, 和 8 被旋转后仍然是它们自己;2 和 5 可以互相旋转成对方(在这种情况下,它们以不同的方向旋转,换句话说,2 和 5 互为镜像);6 和 9 同理,除了这些以外其他的数字旋转以后都不再是有效的数字。
现在我们有一个正整数 N, 计算从 1 到 N 中有多少个数 X 是好数?
示例:
输入: 10 输出: 4 解释: 在[1, 10]中有四个好数: 2, 5, 6, 9。 注意 1 和 10 不是好数, 因为他们在旋转之后不变。
提示:
- N 的取值范围是
[1, 10000]。
解题思路
方法一:直接枚举
一种直观且有效的思路是,直接枚举 中的每个数,判断其是否为好数,若为好数,则答案加一。
那么题目的重点转化为如何判断一个数字 是否为好数。判断的逻辑如下:
我们先用一个长度为 的数组 记录每个有效数字对应的旋转数字,在这道题中,有效数字有 ,分别对应旋转数字 。如果不是有效数字,我们将对应的旋转数字设为 。
然后遍历数字 的每一位数字 ,如果 不是有效数字,说明 不是好数,直接返回 。否则,我们将数字 对应的旋转数字 加入到 中。最后,判断 和 是否相等,若不相等,则说明 是好数,返回 。
时间复杂度 ,其中 为题目给定的数字。空间复杂度 。
相似题目:
class Solution:
def rotatedDigits(self, n: int) -> int:
def check(x):
y, t = 0, x
k = 1
while t:
v = t % 10
if d[v] == -1:
return False
y = d[v] * k + y
k *= 10
t //= 10
return x != y
d = [0, 1, 5, -1, -1, 2, 9, -1, 8, 6]
return sum(check(i) for i in range(1, n + 1))
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity depends on the number of digits in n, since DP iterates over each digit position with a fixed number of states per position, leading to O(d * s) where d is digits and s is state count. Space complexity is similarly O(d * s) for the DP table, often reducible to O(s) with state compression. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Check if the candidate correctly identifies invalid and changeable digits.
- question_mark
Look for proper DP state definition that captures good number formation.
- question_mark
Watch for attempts to brute-force the range instead of using transitions.
常见陷阱
外企场景- error
Failing to mark digits 3, 4, 7 as invalid, which can overcount numbers.
- error
Ignoring numbers that remain unchanged after rotation, counting them incorrectly as good.
- error
Not correctly propagating DP states, leading to undercounting or overcounting sequences.
进阶变体
外企场景- arrow_right_alt
Count rotated numbers in a different base, e.g., base-8 digits with custom rotation rules.
- arrow_right_alt
Determine the largest good number less than or equal to n instead of counting all.
- arrow_right_alt
Include additional digit transformation constraints, such as disallowing consecutive change digits.