把时、分、秒各写成 6 位二进制排成 3×6 矩阵,按列和按行各拼接一次,输出两个 18 位串。
OJ: roj
题目 ID: 10026
难度:入门
标签:字符串模拟进制
创建: 2026-10-02 19:15
更新: 2026-10-04 22:06
题目描述
小 s 想把时间用二进制表示:给定 HH:MM:SS 形式的 24 小时制时刻,把时、分、秒各写成 6 位二进制(补零),排成 3×6 的 01 矩阵,再用两种方式读出两个 18 位串。输入一行一个 XX:XX:XX 时刻;输出一行两个空格隔开的串,前者竖着按列自左向右读(每列自上而下),后者横着把三行首尾相接读。样例输入 10:37:49,样例输出 011001100010100011 001010100101110001。
思路
把时、分、秒分别转成 6 位二进制当作矩阵的三行,再按列和按行各拼接一次,即得两个 18 位串。6 位可表示
参考代码
Python 版:
python
#!/usr/bin/env python3
# Author by Rainboy blog: https://rainboylv.com github: https://github.com/rainboylvx
# rbook: -> https://rbook.roj.ac.cn https://rbook2.roj.ac.cn
# rainboy的学习导航网站: https://idx.roj.ac.cn
# create_at: 2026-10-02 19:33
# update_at: 2026-10-02 19:33
import sys
def encode(time_text: str) -> tuple[str, str]:
"""把 HH:MM:SS 摊成 3×6 比特矩阵,返回竖着按列、横着按行取出的两个 18 位串。"""
# 时、分、秒各补零写成 6 位二进制,各占矩阵一行(时 <= 23、分秒 <= 59 都放得下)
rows = [f"{value:06b}" for value in map(int, time_text.split(":"))] # 3 行
vertical = "".join(map("".join, zip(*rows))) # 按列读:每列自上而下按时、分、秒取
horizontal = "".join(rows) # 按行读:三行首尾相接
return vertical, horizontal
def solve() -> None:
data = iter(sys.stdin.buffer.read().split())
time_text = next(data).decode() # 整行只有一个 HH:MM:SS token
print(*encode(time_text))
if __name__ == "__main__":
solve()C++ 版(同一算法):
cpp
/**
* Author by Rainboy blog: https://rainboylv.com github: https://github.com/rainboylvx
* rbook: -> https://rbook.roj.ac.cn https://rbook2.roj.ac.cn
* rainboy的学习导航网站: https://idx.roj.ac.cn
* create_at: 2026-10-04 22:06
* update_at: 2026-10-04 22:06
*/
#include <iostream>
#include <string>
using namespace std;
typedef long long ll;
int bits[3][6]; // bits[0/1/2][j] 表示时/分/秒的 6 位二进制中从高到低的第 j 位
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
string time_text;
cin >> time_text; // 形如 HH:MM:SS
// 时、分、秒各自拆出 6 位二进制,依次占矩阵的一行(时 <= 23、分秒 <= 59 都放得下)
ll value[3];
value[0] = (time_text[0] - '0') * 10 + (time_text[1] - '0');
value[1] = (time_text[3] - '0') * 10 + (time_text[4] - '0');
value[2] = (time_text[6] - '0') * 10 + (time_text[7] - '0');
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 6; j++) {
bits[i][j] = (value[i] >> (5 - j)) & 1;
}
}
// 竖着取:每列自上而下(时、分、秒),列从左到右
for (int j = 0; j < 6; j++) {
for (int i = 0; i < 3; i++) {
cout << bits[i][j];
}
}
cout << " ";
// 横着取:三行首尾相接
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 6; j++) {
cout << bits[i][j];
}
}
cout << "\n";
return 0;
}