알고리즘 스터디/Python

[LeetCode] 3280. Convert Date to Binary

hkl22 2024. 9. 10. 11:43

3280. Convert Date to Binary

LeetCode

https://leetcode.com/problems/convert-date-to-binary/

문제

  • 문자열 date가 주어졌습니다.
  • date는 yyyy-mm-dd 형식으로 그레고리력 날짜를 나타냅니다.
  • 연도, 월, 일을 각각 2진수로 변환한 후 year-month-date 형식으로 결합한 문자열을 반환하는 코드를 작성하세요.

예제

  • Input: date = "2080-02-29"
  • Output: "100000100000-10-11101"

풀이 과정 #1

  • 주어진 문자열 date를 "-" 기준으로 분리하여 변수 l_date에 저장합니다.
  • 빈 리스트 bin_date를 생성합니다.
  • l_date의 모든 요소를 순회하며 현재 요소(num)를 정수로 변환한 후 2진수로 변환하고 인덱스 슬라이싱으로 접두사 "0b"를 제거하여 bin_date에 추가합니다.
  • 최종적으로 bin_date의 모든 요소를 "-"로 결합하여 문자열로 반환합니다.

코드(Python) #1

class Solution:
    def convertDateToBinary(self, date: str) -> str:
        l_date = date.split("-")
        bin_date = []
        for num in l_date:
            bin_date.append(bin(int(num))[2:])
        return "-".join(bin_date)

풀이 과정 #2

  • 주어진 문자열 date를 "-" 기준으로 분리하여 각각 변수 year, month, day에 저장합니다.
  • year, month, day를 정수로 변환한 후 2진수로 변환하고 인덱스 슬라이싱으로 접두사 "0b"를 제거합니다.
  • 변환된 2진수 문자열들을 "-"로 결합하여 반환합니다.

코드(Python) #2

class Solution:
    def convertDateToBinary(self, date: str) -> str:
        year, month, day = date.split("-")
        year_bin = bin(int(year))[2:]
        month_bin = bin(int(month))[2:]
        day_bin = bin(int(day))[2:]
        return f"{year_bin}-{month_bin}-{day_bin}"

참고

  • bin(숫자) : 주어진 숫자의 2진수 문자열 반환, 문자열의 시작 부분에 접두사 "0b"가 붙음