Skip to main content

Date to Binary

KANISHKA GUPTA
EditReport

Leetcode: Problem-3280

Description:

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.

Video Explanation

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.

Steps:

1. Date Input: Given a date in the format YYYY-MM-DD.

2. Binary Conversion:

• Convert the year (YYYY) to binary. • Convert the month (MM) to binary. • Convert the day (DD) to binary.

3. Output: Provide the combined binary representation.

Solutions

class Solution {
public:
string convertDateToBinary(string date) {
int year = stoi(date.substr(0, 4));
int month = stoi(date.substr(5, 2));
int day = stoi(date.substr(8, 2));

auto toBin = [](int val) {
string s = "";
while (val > 0) {
s = to_string(val % 2) + s;
val /= 2;
}
return s;
};

return toBin(year) + "-" + toBin(month) + "-" + toBin(day);
}
};
Track Your Progress

Done with this topic? Mark it as complete to track your progress.

💬 Discuss this page

Have a question or spot something confusing in "Date to Binary"? Ask below — it's backed by GitHub Discussions, so maintainers get notified like any other GitHub activity.