Skip to content

3280. Convert Date to Binary 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
 public:
  string convertDateToBinary(string date) {
    const int year = stoi(date.substr(0, 4));
    const int month = stoi(date.substr(5, 2));
    const int day = stoi(date.substr(8, 2));
    return toBinary(year) + '-' + toBinary(month) + '-' + toBinary(day);
  }

 private:
  // Converts an integer to binary without leading zeros.
  string toBinary(int value) {
    const string binary = bitset<16>(value).to_string();
    return binary.substr(binary.find('1'));  // Remove leading zeros.
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
  public String convertDateToBinary(String date) {
    final int year = Integer.parseInt(date.substring(0, 4));
    final int month = Integer.parseInt(date.substring(5, 7));
    final int day = Integer.parseInt(date.substring(8, 10));
    StringBuilder sb = new StringBuilder();
    sb.append(Integer.toBinaryString(year))
        .append("-")
        .append(Integer.toBinaryString(month))
        .append("-")
        .append(Integer.toBinaryString(day));
    return sb.toString();
  }
}
1
2
3
4
5
6
7
8
9
class Solution:
  def convertDateToBinary(self, date: str) -> str:
    year, month, day = map(int, date.split('-'))

    def toBinary(value: int) -> str:
      """Converts an integer to binary without leading zeros."""
      return bin(value)[2:]

    return '-'.join([toBinary(year), toBinary(month), toBinary(day)])