Convert Date to Binary
EasyPrompt
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 == 10date[4] == date[7] == '-', and all otherdate[i]'s are digits.- The input is generated such that
daterepresents a valid Gregorian calendar date between Jan 1st, 1900 and Dec 31st, 2100 (both inclusive).
Approaches
2 approaches with complexity analysis and trade-offs.
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.
Algorithm
- Parse the input
datestringyyyy-mm-ddto extract the year, month, and day components. This can be done usingsubstringdue 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
nis 0, returning"0". - Use a
whileloop that continues as long asn > 0. - In each iteration, calculate the remainder
n % 2and append it to aStringBuilder. - Update
nby integer division:n = n / 2. - After the loop, the
StringBuildercontains the binary digits in reverse order. Reverse theStringBuilderand convert it to a string.
- Handle the edge case where
- Call this
toBinaryManualfunction for the year, month, and day integers. - Concatenate the resulting binary strings with
"-"as a separator to form the final output string.
Walkthrough
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.
Complexity
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.
Trade-offs
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.
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.
Algorithm
- Split the input
datestring by the"-"delimiter using theString.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 usingInteger.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 aStringBuilderis efficient for this task.
Walkthrough
This is the most straightforward and idiomatic way to solve the problem in Java. The solution is broken down into simple, clear steps.
- Parsing: The
date.split("-")method is called to effortlessly break the input string into its three constituent parts: year, month, and day. - String-to-Integer Conversion: Each part, which is a string, is converted to an integer using
Integer.parseInt(). - 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). - Concatenation: The resulting binary strings for year, month, and day are joined together with hyphens to form the final output. A
StringBuilderis used for efficient string construction.
This method minimizes custom logic, reducing the chances of errors and making the code easy to understand and maintain.
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(); }}Complexity
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.
Trade-offs
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.
Solutions
Solution
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); }}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)); }};class Solution: def convertDateToBinary(self, date: str) -> str: return "-" . join(f " { int ( s ) : b } " for s in date . split("-"))Video walkthrough
Newsletter
One sharp idea, every week
System design and interview prep — short enough to finish.
No spam. Unsubscribe anytime.
Practice
Same difficulty — related problems to reinforce the pattern.