LeetCode 题解工作台

将整数转换为两个无零整数的和

「无零整数」是十进制表示中 不含任何 0 的正整数。 给你一个整数 n ,请你返回一个 由两个整数组成的列表 [a, b] ,满足: a 和 b 都是无零整数 a + b = n 题目数据保证至少有一个有效的解决方案。 如果存在多个有效解决方案,你可以返回其中任意一个。 示例 1: 输入: n = …

category

1

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

简单 · 数学·driven

bolt

答案摘要

从 开始枚举 ,那么 $b = n - a$。对于每个 和 ,我们将它们转换为字符串并且连接起来,然后判断是否包含字符 `'0'`,如果不包含,那么就找到了答案,返回 $[a, b]$。 时间复杂度 $O(n \times \log n)$,其中 为题目给定的整数。空间复杂度 $O(\log n)$。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

「无零整数」是十进制表示中 不含任何 0 的正整数。

给你一个整数 n,请你返回一个 由两个整数组成的列表 [a, b],满足:

  • ab 都是无零整数
  • 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
lightbulb

解题思路

方法一:直接枚举

11 开始枚举 aa,那么 b=nab = n - a。对于每个 aabb,我们将它们转换为字符串并且连接起来,然后判断是否包含字符 '0',如果不包含,那么就找到了答案,返回 [a,b][a, b]

时间复杂度 O(n×logn)O(n \times \log n),其中 nn 为题目给定的整数。空间复杂度 O(logn)O(\log n)

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

复杂度分析

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

面试官常问的追问

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

warning

常见陷阱

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

swap_horiz

进阶变体

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

help

常见问题

外企场景

将整数转换为两个无零整数的和题解:数学·driven | LeetCode #1317 简单