DEV Community

Ben Pereira
Ben Pereira

Posted on

Leetcode — 3280. Convert Date to Binary

It’s an easy problem with description being:

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).

To solve this issue you could go straight forward splitting the string using split method, then using toBinaryString from Integer (which needs to change string to int, so a parse also will be needed) and will be like:

class Solution {
    public String convertDateToBinary(String date) {

        final String[] split = date.split("-");

        final StringBuilder response = new StringBuilder();

        response.append(Integer.toBinaryString(Integer.parseInt(split[0])));
        response.append("-");
        response.append(Integer.toBinaryString(Integer.parseInt(split[1])));
        response.append("-");
        response.append(Integer.toBinaryString(Integer.parseInt(split[2])));

        return response.toString();
    }
}
Enter fullscreen mode Exit fullscreen mode

Runtime: 3ms, faster than 84.12% of Java online submissions.

Memory Usage: 42.91 MB, less than 26.24% of Java online submissions.

If you want to keep more elegant but at a bit cost of processing you can use stream, not the fastest but sure the cleaner:

class Solution {
    public String convertDateToBinary(String date) {
        return Arrays.stream(date.split("-")) // split date into 3 parts
                .map(Integer::parseInt) // parse to int
                .map(Integer::toBinaryString) // parse to binary string
                .collect(Collectors.joining("-")); // join by hifen
    }
}
Enter fullscreen mode Exit fullscreen mode

Runtime: 10ms, faster than 8.73% of Java online submissions.

Memory Usage: 42.90 MB, less than 34.55% of Java online submissions.

That’s it! If there is anything thing else to discuss feel free to drop a comment, if I missed anything let me know so I can update accordingly.

Until next post! :)

Top comments (0)