闯关leetcode——3280. Convert Date to Binary
大纲
- 题目
- 地址
- 内容
- 解题
- 代码地址
题目
地址
https://leetcode.com/problems/convert-date-to-binary/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.
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).
解题
这题就是要将一个10进制表示的日期类型字符串转换成一个2进制表示的日期类型字符串。这题有很强的条件限定,比如:总长度一定是10,下标4和7的位置的字符一定是“-”。我们可以充分利用这些条件来简化代码。
#include <string>
using namespace std;
class Solution {
public:
string convertDateToBinary(string date) {
return toBinary(stoi(date.substr(0, 4))) + "-" + toBinary(stoi(date.substr(5, 2))) + "-" + toBinary(stoi(date.substr(8, 2)));
}
private:
string toBinary(int num) {
string result = "";
while (num > 0) {
if (num & 1) {
result = "1" + result;
} else {
result = "0" + result;
}
num >>= 1;
}
return result;
}
};
代码地址
https://github.com/f304646673/leetcode/tree/main/3280-Convert-Date-to-Binary/cplusplus