二进制手表
原题在这里:
概述:
给定4位和6位二进制位,分别用于表示数字[0,11],[0,59],问有n位二进制生效时候所表示的时间字符串数组。
analyse:
1.直接思路就是dfs暴力构造了,但是这就增加了本题的难度,但是我还是写出来了,问题不大。
code:

class Solution { vector<int> num; void get_num(int x, int y, int z, int n, int m) //二进制长度,当前i,当前数值, 当前选用个数 { if (x == y || n == 0) { if (n == 0 && z < m) num.emplace_back(z); return; } get_num(x, y + 1, z, n, m); get_num(x, y + 1, z + (int)pow(2, x - y - 1), n - 1, m); } vector<int> read(int x, int y, int z, int n, int m) { num.clear(); get_num(x, y, z, n, m); return num; } string ch(int x, bool pd) { if (x == 0) return pd ? "00" : "0"; string ans; while (x) { ans = (char)(x % 10 + '0') + ans; x /= 10; } return ans.size() > 1 ? ans : (pd ? "0" : "") + ans; } void pr(vector<int> num) { for (int i : num) cout << i << ' '; cout << endl; } public: vector<string> readBinaryWatch(int turnedOn) { int n = turnedOn; vector<string> ans; for (int i = 0; i <= 4; ++i) { for (int j = 0; j <= 6; ++j) { if (i + j != n) continue; //数组转多个字符串匹配 vector<int> p = read(4, 0, 0, i, 12); vector<int> q = read(6, 0, 0, j, 60); // cout << i << " , " << j << "输出两数组如下:" << endl; // pr(p); // pr(q); for (int y : q) for (int x : p) ans.emplace_back(ch(x, false) + ":" + ch(y, true)); } } // sort(ans.begin(),ans.end()); return ans; } };
多动脑子还是好的,这个题我就属于不懂变通了。
2.逆向思维,遍历时间检验当前时间的二进制位是否符号n位。
code:
class Solution { int gn(int x) { int ans = 0; while (x) x = x & (x - 1), ans++; return ans; } string ch(int x) { if (x == 0) return "0"; string ans; while (x) { ans = (char)(x % 10 + '0') + ans; x /= 10; } return ans; } public: vector<string> readBinaryWatch(int turnedOn) { int n = turnedOn; vector<string> ans; for (int i = 0; i < 12; ++i) { for (int j = 0; j < 60; ++j) { if (gn(i) + gn(j) == n) { string p = ch(i); string q = ch(j); if (q.length() < 2) q = "0" + q; ans.emplace_back(p + ":" + q); } } } return ans; } };
【Over】
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
· 零经验选手,Compose 一天开发一款小游戏!