LeetCode 题解工作台
统计好数字的数目
我们称一个数字字符串是 好数字 当它满足(下标从 0 开始) 偶数 下标处的数字为 偶数 且 奇数 下标处的数字为 质数 ( 2 , 3 , 5 或 7 )。 比方说, "2582" 是好数字,因为偶数下标处的数字( 2 和 8 )是偶数且奇数下标处的数字( 5 和 2 )为质数。但 "3245" …
2
题型
5
代码语言
3
相关题
当前训练重点
中等 · 数学·递归
答案摘要
长度为 的好数字,偶数下标一共有 $\lceil \frac{n}{2} \rceil = \lfloor \frac{n + 1}{2} \rfloor$ 位,偶数下标可以填入 种数字($0, 2, 4, 6, 8$);奇数下标一共有 $\lfloor \frac{n}{2} \rfloor$ 位,奇数下标可以填入 种数字($2, 3, 5, 7$)。因此长度为 的好数字的个数为: $$
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数学·递归 题型思路
题目描述
我们称一个数字字符串是 好数字 当它满足(下标从 0 开始)偶数 下标处的数字为 偶数 且 奇数 下标处的数字为 质数 (2,3,5 或 7)。
- 比方说,
"2582"是好数字,因为偶数下标处的数字(2和8)是偶数且奇数下标处的数字(5和2)为质数。但"3245"不是 好数字,因为3在偶数下标处但不是偶数。
给你一个整数 n ,请你返回长度为 n 且为好数字的数字字符串 总数 。由于答案可能会很大,请你将它对 109 + 7 取余后返回 。
一个 数字字符串 是每一位都由 0 到 9 组成的字符串,且可能包含前导 0 。
示例 1:
输入:n = 1 输出:5 解释:长度为 1 的好数字包括 "0","2","4","6","8" 。
示例 2:
输入:n = 4 输出:400
示例 3:
输入:n = 50 输出:564908303
提示:
1 <= n <= 1015
解题思路
方法一:快速幂
长度为 的好数字,偶数下标一共有 位,偶数下标可以填入 种数字();奇数下标一共有 位,奇数下标可以填入 种数字()。因此长度为 的好数字的个数为:
我们可以使用快速幂来计算 和 ,时间复杂度为 ,空间复杂度为 。
class Solution:
def countGoodNumbers(self, n: int) -> int:
mod = 10**9 + 7
return pow(5, (n + 1) >> 1, mod) * pow(4, n >> 1, mod) % mod
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(log n) due to fast exponentiation recursion, and space complexity is O(1) since no additional arrays or recursion stacks grow with n. |
| 空间 | O(1) |
面试官常问的追问
外企场景- question_mark
Check if candidate recognizes the even/prime index pattern immediately.
- question_mark
Watch for attempts to generate all strings, which fails for large n.
- question_mark
Listen for use of fast power recursion or modular arithmetic, signaling optimal approach.
常见陷阱
外企场景- error
Trying to enumerate all strings leads to memory overflow or timeout.
- error
Miscounting even vs odd positions when n is odd.
- error
Neglecting modulo operation and causing integer overflow.
进阶变体
外企场景- arrow_right_alt
Change the set of prime digits or even digits to test adaptability of the power calculation.
- arrow_right_alt
Ask for sum of digits of all good numbers instead of count, requiring extension of the pattern.
- arrow_right_alt
Restrict digit strings to exclude leading zeros, modifying the first position choices.