LeetCode 题解工作台
将整数转换为两个无零整数的和
「无零整数」是十进制表示中 不含任何 0 的正整数。 给你一个整数 n ,请你返回一个 由两个整数组成的列表 [a, b] ,满足: a 和 b 都是无零整数 a + b = n 题目数据保证至少有一个有效的解决方案。 如果存在多个有效解决方案,你可以返回其中任意一个。 示例 1: 输入: n = …
1
题型
6
代码语言
3
相关题
当前训练重点
简单 · 数学·driven
答案摘要
从 开始枚举 ,那么 $b = n - a$。对于每个 和 ,我们将它们转换为字符串并且连接起来,然后判断是否包含字符 `'0'`,如果不包含,那么就找到了答案,返回 $[a, b]$。 时间复杂度 $O(n \times \log n)$,其中 为题目给定的整数。空间复杂度 $O(\log n)$。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数学·driven 题型思路
题目描述
「无零整数」是十进制表示中 不含任何 0 的正整数。
给你一个整数 n,请你返回一个 由两个整数组成的列表 [a, b],满足:
a和b都是无零整数a + b = n
题目数据保证至少有一个有效的解决方案。
如果存在多个有效解决方案,你可以返回其中任意一个。
示例 1:
输入:n = 2 输出:[1,1] 解释:a = 1, b = 1。a + b = n 并且 a 和 b 的十进制表示形式都不包含任何 0。
示例 2:
输入:n = 11 输出:[2,9]
示例 3:
输入:n = 10000 输出:[1,9999]
示例 4:
输入:n = 69 输出:[1,68]
示例 5:
输入:n = 1010 输出:[11,999]
提示:
2 <= n <= 104
解题思路
方法一:直接枚举
从 开始枚举 ,那么 。对于每个 和 ,我们将它们转换为字符串并且连接起来,然后判断是否包含字符 '0',如果不包含,那么就找到了答案,返回 。
时间复杂度 ,其中 为题目给定的整数。空间复杂度 。
class Solution:
def getNoZeroIntegers(self, n: int) -> List[int]:
for a in count(1):
b = n - a
if "0" not in f"{a}{b}":
return [a, b]
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n * d) where d is the number of digits in each candidate because each number requires a digit scan. Space complexity is O(1) aside from the output, since only a few variables are stored. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Expect a simple iteration solution that respects the no-zero constraint.
- question_mark
Check if candidates are properly validated for zero digits, not just summed to n.
- question_mark
Look for early exit and helper function separation as signs of clear implementation.
常见陷阱
外企场景- error
Returning a pair without checking zero digits can lead to wrong solutions.
- error
Assuming only one solution exists may cause unnecessary complexity.
- error
Checking digits incorrectly or using arithmetic tricks can fail on numbers containing 0s internally.
进阶变体
外企场景- arrow_right_alt
Find three positive integers summing to n, all without zero digits.
- arrow_right_alt
Count all pairs of no-zero integers that sum to n.
- arrow_right_alt
Modify to exclude numbers containing a specific forbidden digit other than zero.