系列文章目录
【拒绝算法PUA】0x00-位运算
【拒绝算法PUA】0x01- 区间比较技巧
【拒绝算法PUA】0x02- 区间合并技巧
【拒绝算法PUA】0x03 - LeetCode 排序类型刷题
【拒绝算法PUA】LeetCode每日一题系列刷题汇总-2025年持续刷新中
C++刷题技巧总结:
[温习C/C++]0x04 刷题基础编码技巧
LeetCode 3280. 将日期转换为二进制表示
链接
题目
给你一个字符串 date,它的格式为 yyyy-mm-dd,表示一个公历日期。
date 可以重写为二进制表示,只需要将年、月、日分别转换为对应的二进制表示(不带前导零)并遵循 year-month-day 的格式。
返回 date 的 二进制 表示。
示例 1:
输入: date = “2080-02-29”
输出: “100000100000-10-11101”
解释:
100000100000, 10 和 11101 分别是 2080, 02 和 29 的二进制表示。
示例 2:
输入: date = “1900-01-01”
输出: “11101101100-1-1”
解释:
11101101100, 1 和 1 分别是 1900, 1 和 1 的二进制表示。
提示:
date.length == 10
date[4] == date[7] == ‘-’,其余的 date[i] 都是数字。
输入保证 date 代表一个有效的公历日期,日期范围从 1900 年 1 月 1 日到 2100 年 12 月 31 日(包括这两天)。
解题方法1
#include <iostream>
#include <string>
#include <sstream>
#include <bitset>
using namespace std;
class Solution {
public:
string convertDateToBinary(string date) {
string res;
string val;
const char delim = '-';
std::stringstream ss(date);
for (string num; getline(ss, num, delim);) {
int n = std::stoi(num);
string bit_str = std::bitset<16>(n).to_string();
string trim_val = trim0(bit_str);
res.append(trim_val).append("-");
}
res.erase(res.size() - 1);
return res;
}
string trim0(std::string& bitStr) {
string trimStr;
bool firstNonZero = false;
for (char cc : bitStr) {
if (cc != '0' && !firstNonZero) {
firstNonZero = true;
trimStr.push_back(cc);
continue;
}
if (firstNonZero) {
trimStr.push_back(cc);
}
}
return trimStr;
}
};
int main(int argc, char **argv) {
Solution obj;
string date1 = "2080-02-29";
string res1 = obj.convertDateToBinary(date1);
cout << res1 << endl;
return 0;
}
解题方法2
#include <iostream>
#include <string>
#include <sstream>
#include <bitset>
using namespace std;
class Solution {
public:
string convertDateToBinary(string date) {
string res;
auto bin = [](int x) -> string {
string bits = bitset<16>(x).to_string();
int idx = bits.find("1");
return bits.substr(idx);
};
string year = bin(std::stoi(date.substr(0, 4)));
string month = bin(std::stoi(date.substr(5, 2)));
string day = bin(std::stoi(date.substr(8, 2)));
res.append(year).append("-").append(month).append("-").append(day);
return res;
}
};
int main(int argc, char **argv) {
Solution obj;
string date1 = "2080-02-29";
string res1 = obj.convertDateToBinary(date1);
cout << res1 << endl;
return 0;
}