LeetCode 题解工作台

统计好数字的数目

我们称一个数字字符串是 好数字 当它满足(下标从 0 开始) 偶数 下标处的数字为 偶数 且 奇数 下标处的数字为 质数 ( 2 , 3 , 5 或 7 )。 比方说, "2582" 是好数字,因为偶数下标处的数字( 2 和 8 )是偶数且奇数下标处的数字( 5 和 2 )为质数。但 "3245" …

category

2

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

中等 · 数学·递归

bolt

答案摘要

长度为 的好数字,偶数下标一共有 $\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 AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数学·递归 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

我们称一个数字字符串是 好数字 当它满足(下标从 0 开始)偶数 下标处的数字为 偶数 且 奇数 下标处的数字为 质数 (235 或 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
lightbulb

解题思路

方法一:快速幂

长度为 nn 的好数字,偶数下标一共有 n2=n+12\lceil \frac{n}{2} \rceil = \lfloor \frac{n + 1}{2} \rfloor 位,偶数下标可以填入 55 种数字(0,2,4,6,80, 2, 4, 6, 8);奇数下标一共有 n2\lfloor \frac{n}{2} \rfloor 位,奇数下标可以填入 44 种数字(2,3,5,72, 3, 5, 7)。因此长度为 nn 的好数字的个数为:

ans=5n2×4n2ans = 5^{\lceil \frac{n}{2} \rceil} \times 4^{\lfloor \frac{n}{2} \rfloor}

我们可以使用快速幂来计算 5n25^{\lceil \frac{n}{2} \rceil}4n24^{\lfloor \frac{n}{2} \rfloor},时间复杂度为 O(logn)O(\log n),空间复杂度为 O(1)O(1)

1
2
3
4
5
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
speed

复杂度分析

指标
时间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)
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

统计好数字的数目题解:数学·递归 | LeetCode #1922 中等