LeetCode 题解工作台

将日期转换为二进制表示

给你一个字符串 date ,它的格式为 yyyy-mm-dd ,表示一个公历日期。 date 可以重写为二进制表示,只需要将年、月、日分别转换为对应的二进制表示(不带前导零)并遵循 year-month-day 的格式。 返回 date 的 二进制 表示。 示例 1: 输入: date = "208…

category

2

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

简单 · 数学·string

bolt

答案摘要

我们先将字符串 按照 `-` 分割,然后将每个部分转换为二进制表示,最后将这三个部分用 `-` 连接起来即可。 时间复杂度 ,空间复杂度 。其中 为字符串 的长度。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个字符串 date,它的格式为 yyyy-mm-dd,表示一个公历日期。

date 可以重写为二进制表示,只需要将年、月、日分别转换为对应的二进制表示(不带前导零)并遵循 year-month-day 的格式。

返回 date二进制 表示。

 

示例 1:

输入: date = "2080-02-29"

输出: "100000100000-10-11101"

解释:

100000100000, 10 和 11101 分别是 2080, 02 和 29 的二进制表示。

示例 2:

输入: date = "1900-01-01"

输出: "11101101100-1-1"

解释:

11101101100, 1 和 1 分别是 1900, 1 和 1 的二进制表示。

 

提示:

  • date.length == 10
  • date[4] == date[7] == '-',其余的 date[i] 都是数字。
  • 输入保证 date 代表一个有效的公历日期,日期范围从 1900 年 1 月 1 日到 2100 年 12 月 31 日(包括这两天)。
lightbulb

解题思路

方法一:模拟

我们先将字符串 date\textit{date} 按照 - 分割,然后将每个部分转换为二进制表示,最后将这三个部分用 - 连接起来即可。

时间复杂度 O(n)O(n),空间复杂度 O(n)O(n)。其中 nn 为字符串 date\textit{date} 的长度。

1
2
3
4
class Solution:
    def convertDateToBinary(self, date: str) -> str:
        return "-".join(f"{int(s):b}" for s in date.split("-"))
speed

复杂度分析

指标
时间complexity is O(1) because the date string has a fixed length of 10 characters and each conversion is constant time. Space complexity is O(1) since only a few variables are used for splitting and storing binary results.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Watch for handling leading zeros incorrectly when converting each date part to binary.

  • question_mark

    Verify that month and day conversions correctly handle single-digit values.

  • question_mark

    Ensure concatenation preserves the yyyy-mm-dd order after conversion.

warning

常见陷阱

外企场景
  • error

    Including leading zeros in the binary representations which violates the output format.

  • error

    Misinterpreting the '-' positions and corrupting the date order in the final string.

  • error

    Using string conversion without casting to integer first, which can lead to incorrect binary values.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Convert a time string hh:mm:ss to binary format using the same approach for hours, minutes, and seconds.

  • arrow_right_alt

    Return the binary date but pad each component to a fixed length, testing understanding of optional formatting.

  • arrow_right_alt

    Convert a list of multiple date strings to binary in bulk, emphasizing iteration over parsing and conversion logic.

help

常见问题

外企场景

将日期转换为二进制表示题解:数学·string | LeetCode #3280 简单