LeetCode 题解工作台

十-二进制数的最少数目

如果一个十进制数字不含任何前导零,且每一位上的数字不是 0 就是 1 ,那么该数字就是一个 十-二进制数 。例如, 101 和 1100 都是 十-二进制数 ,而 112 和 3001 不是。 给你一个表示十进制整数的字符串 n ,返回和为 n 的 十-二进制数 的最少数目。 示例 1: 输入: n…

category

2

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

中等 · 贪心·invariant

bolt

答案摘要

题目等价于找字符串中的最大数。 时间复杂度 ,其中 为字符串长度。空间复杂度 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 贪心·invariant 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

如果一个十进制数字不含任何前导零,且每一位上的数字不是 0 就是 1 ,那么该数字就是一个 十-二进制数 。例如,1011100 都是 十-二进制数,而 1123001 不是。

给你一个表示十进制整数的字符串 n ,返回和为 n十-二进制数 的最少数目。

 

示例 1:

输入:n = "32"
输出:3
解释:10 + 11 + 11 = 32

示例 2:

输入:n = "82734"
输出:8

示例 3:

输入:n = "27346209830709182346"
输出:9

 

提示:

  • 1 <= n.length <= 105
  • n 仅由数字组成
  • n 不含任何前导零并总是表示正整数
lightbulb

解题思路

方法一:脑筋急转弯

题目等价于找字符串中的最大数。

时间复杂度 O(n)O(n),其中 nn 为字符串长度。空间复杂度 O(1)O(1)

1
2
3
4
class Solution:
    def minPartitions(self, n: str) -> int:
        return int(max(n))
speed

复杂度分析

指标
时间complexity depends on iterating through each digit of n. Space complexity involves tracking values through each iteration but remains manageable within the input constraints.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Ability to apply greedy algorithms effectively.

  • question_mark

    Understanding how to reduce a problem to simpler subproblems.

  • question_mark

    Proficiency in validating constraints and invariants in problem-solving.

warning

常见陷阱

外企场景
  • error

    Forgetting to handle multiple digits efficiently while maintaining a greedy approach.

  • error

    Not ensuring that deci-binary numbers are constructed correctly according to the problem's rules.

  • error

    Misunderstanding the greedy choice strategy and missing edge cases.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Handling very large input sizes efficiently.

  • arrow_right_alt

    Modifying the problem to use other number systems.

  • arrow_right_alt

    Optimizing space complexity while maintaining time efficiency.

help

常见问题

外企场景

十-二进制数的最少数目题解:贪心·invariant | LeetCode #1689 中等