# Convert Date to Binary
**Difficulty:** EASY
[External](https://leetcode.com/problems/convert-date-to-binary)
Canonical: https://scaleengineer.com/dsa/problems/convert-date-to-binary
**Patterns:** [Math](https://scaleengineer.com/dsa/patterns/math)
**Data structures:** String
---
## Problem
You are given a string `date` representing a Gregorian calendar date in the `yyyy-mm-dd` format.

`date` can be written in its binary representation obtained by converting year, month, and day to their binary representations without any leading zeroes and writing them down in `year-month-day` format.

Return the **binary** representation of `date`.

**Example 1:**

**Input:** date = "2080-02-29"

**Output:** "100000100000-10-11101"

**Explanation:**

100000100000, 10, and 11101 are the binary representations of 2080, 02, and 29 respectively.

**Example 2:**

**Input:** date = "1900-01-01"

**Output:** "11101101100-1-1"

**Explanation:**

11101101100, 1, and 1 are the binary representations of 1900, 1, and 1 respectively.

**Constraints:**

* `date.length == 10`
* `date[4] == date[7] == '-'`, and all other `date[i]`'s are digits.
* The input is generated such that `date` represents a valid Gregorian calendar date between Jan 1st, 1900 and Dec 31st, 2100 (both inclusive).

# Approaches
## Approach 1: Manual Binary Conversion
This approach involves implementing the integer-to-binary conversion logic from scratch. While it correctly solves the problem, it is generally less efficient in terms of development time and code conciseness compared to using built-in library functions. It manually calculates the binary representation of the year, month, and day after parsing them from the input string.
**Time:** O(1) - The time complexity is constant. The input string has a fixed length, and the numerical values of year, month, and day are within a small, fixed range. The number of operations for splitting, parsing, and converting to binary (which takes `O(log k)` for a number `k`, but `k` is bounded) is constant. · **Space:** O(1) - The space required is constant. The `parts` array, the `StringBuilder` for binary conversion (max length is `log2(2100)`, which is constant), and the final result string all have sizes that are bounded by a constant, not dependent on any variable input size.
**Pros:** Demonstrates a fundamental understanding of number base conversion algorithms.; Independent of specific library functions for the core conversion logic.
**Cons:** More verbose and requires writing more code.; Reinvents functionality that is already available in the standard library.; Higher chance of introducing bugs during the implementation of the binary conversion logic.; May be slightly less performant in practice compared to highly optimized native library functions.
### Explanation
The process begins by parsing the date string. Since the format `yyyy-mm-dd` is fixed, we can reliably split the string by the hyphen `'-'` to get the year, month, and day as separate strings. These strings are then converted into their corresponding integer values.

The core of this approach is a custom method for converting an integer to a binary string. This is typically done using the division-by-2 algorithm. We repeatedly take the integer modulo 2 to get the least significant binary digit and then divide the integer by 2 to process the next digit. These digits are collected in reverse order, so a final reversal step is needed to obtain the correct binary string. This process is applied to the year, month, and day integers. Finally, the three resulting binary strings are concatenated, separated by hyphens, to produce the final output.
### Algorithm
- Parse the input `date` string `yyyy-mm-dd` to extract the year, month, and day components. This can be done using `substring` due to the fixed format or by splitting the string by the `'-'` delimiter.
- Convert the extracted string components for year, month, and day into integer values using `Integer.parseInt()`.
- Implement a helper function, let's call it `toBinaryManual(int n)`, to convert an integer to its binary string representation.
- Inside `toBinaryManual(n)`:
  - Handle the edge case where `n` is 0, returning `"0"`.
  - Use a `while` loop that continues as long as `n > 0`.
  - In each iteration, calculate the remainder `n % 2` and append it to a `StringBuilder`.
  - Update `n` by integer division: `n = n / 2`.
  - After the loop, the `StringBuilder` contains the binary digits in reverse order. Reverse the `StringBuilder` and convert it to a string.
- Call this `toBinaryManual` function for the year, month, and day integers.
- Concatenate the resulting binary strings with `"-"` as a separator to form the final output string.

## Approach 2: Using Built-in Functions
This approach leverages Java's built-in functions to provide a concise, readable, and efficient solution. It uses `String.split()` for parsing the date and `Integer.toBinaryString()` for the conversion, which simplifies the code and relies on optimized, standard library implementations.
**Time:** O(1) - The overall time complexity is constant. All operations (`split`, `parseInt`, `toBinaryString`, `append`) run in constant time because their inputs (string length, number of parts, magnitude of numbers) are bounded by the problem constraints. · **Space:** O(1) - The space used for the string array from `split()` and the `StringBuilder` is constant, as the input string length and the size of the numerical parts are fixed.
**Pros:** Highly efficient and concise due to the use of optimized built-in functions.; Code is easy to read, write, and maintain.; Less error-prone as the complex logic is handled by the standard library.
**Cons:** Abstracts away the underlying conversion algorithm, which might not be desirable if the goal is to test fundamental algorithm knowledge.
### Explanation
This is the most straightforward and idiomatic way to solve the problem in Java. The solution is broken down into simple, clear steps.

1.  **Parsing**: The `date.split("-")` method is called to effortlessly break the input string into its three constituent parts: year, month, and day.
2.  **String-to-Integer Conversion**: Each part, which is a string, is converted to an integer using `Integer.parseInt()`.
3.  **Integer-to-Binary Conversion**: The `Integer.toBinaryString()` method is called on each of the three integers. This powerful built-in function handles the entire conversion process, returning the binary representation as a string, exactly as required by the problem (e.g., no leading zeros).
4.  **Concatenation**: The resulting binary strings for year, month, and day are joined together with hyphens to form the final output. A `StringBuilder` is used for efficient string construction.

This method minimizes custom logic, reducing the chances of errors and making the code easy to understand and maintain.

```java
import java.lang.StringBuilder;

class Solution {
    public String dateToBinary(String date) {
        String[] parts = date.split("-");
        
        // Parse string parts to integers
        int year = Integer.parseInt(parts[0]);
        int month = Integer.parseInt(parts[1]);
        int day = Integer.parseInt(parts[2]);
        
        // Convert integers to binary strings
        String binaryYear = Integer.toBinaryString(year);
        String binaryMonth = Integer.toBinaryString(month);
        String binaryDay = Integer.toBinaryString(day);
        
        // Build the final result string
        StringBuilder result = new StringBuilder();
        result.append(binaryYear);
        result.append("-");
        result.append(binaryMonth);
        result.append("-");
        result.append(binaryDay);
        
        return result.toString();
    }
}
```
### Algorithm
- Split the input `date` string by the `"-"` delimiter using the `String.split()` method. This will produce an array of strings: `["yyyy", "mm", "dd"]`.
- Convert the first element of the array (`parts[0]`) to an integer representing the year using `Integer.parseInt()`.
- Convert the second element (`parts[1]`) to an integer for the month.
- Convert the third element (`parts[2]`) to an integer for the day.
- Use the built-in `Integer.toBinaryString()` method to convert each integer (year, month, day) into its binary string representation. This method directly provides the required format without leading zeros.
- Concatenate the three binary strings, with a `"-"` character separating them. Using a `StringBuilder` is efficient for this task.

# Solutions
### Java

```java
class Solution {
public
  String convertDateToBinary(String date) {
    List<String> ans = new ArrayList<>();
    for (var s : date.split("-")) {
      int x = Integer.parseInt(s);
      ans.add(Integer.toBinaryString(x));
    }
    return String.join("-", ans);
  }
}

```

### CPP

```cpp
class Solution {
public:
  string convertDateToBinary(string date) {
    auto bin = [](string s) -> string {
      string t = bitset<32>(stoi(s)).to_string();
      return t.substr(t.find('1'));
    };
    return bin(date.substr(0, 4)) + "-" + bin(date.substr(5, 2)) + "-" +
           bin(date.substr(8, 2));
  }
};

```

### Python

```python
class Solution:
    def convertDateToBinary(self, date: str) -> str: return "-" . join(f " { int ( s ) : b } " for s in date . split("-"))

```
