We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Convert Date to Binary

Number: 3567

Difficulty: Easy

Paid? No

Companies: N/A


Problem Description

Given a date string in the "yyyy-mm-dd" format, convert each part (year, month, day) to its binary representation without leading zeroes, and then concatenate them using dashes, resulting in "binaryYear-binaryMonth-binaryDay".


Key Insights

  • Split the input date string by the dash '-' to extract year, month, and day.
  • Convert each of these string values to integers.
  • Convert the integers to their binary representation without any extra prefix or leading zeroes.
  • Concatenate the binary representations back with dashes.

Space and Time Complexity

Time Complexity: O(1) — the operations are fixed and independent of input size. Space Complexity: O(1) — storage is constant regardless of input.


Solution

The solution involves simple string manipulation and integer conversion. We first split the date string into three parts. Then, we convert each part from a decimal string to an integer and subsequently to a binary string, omitting any leading zeros or prefixes. Finally, we rebuild the result string with the binary representations of the year, month, and day separated by dashes. The approach uses basic operations and does not require any additional data structures aside from temporary variables.


Code Solutions

# Function to convert date to binary representation in Python
def convertDateToBinary(date: str) -> str:
    # Split the input date string into year, month, and day
    year_str, month_str, day_str = date.split('-')
    
    # Convert each part to an integer, then to a binary string without the '0b' prefix
    binary_year = bin(int(year_str))[2:]
    binary_month = bin(int(month_str))[2:]
    binary_day = bin(int(day_str))[2:]
    
    # Concatenate the binary representations with dashes and return the result
    return f"{binary_year}-{binary_month}-{binary_day}"

# Example usage:
# print(convertDateToBinary("2080-02-29"))
← Back to All Questions