Every day a leetcode
题目来源:401. 二进制手表
解法1:枚举
枚举所有时刻,每当小时和分钟的二进制中1的个数之和为turnedOn,则将其加入到答案中。
注:__builtin_popcount()函数用于计算一个 32 位无符号整数有多少个位为1。
注意小时不会以零开头,分钟必须由两位数组成,可能会以零开头。
代码:
/*
* @lc app=leetcode.cn id=401 lang=cpp
*
* [401] 二进制手表
*/
// @lc code=start
class Solution
{
public:
vector<string> readBinaryWatch(int turnedOn)
{
vector<string> ans;
string temp;
for (int h = 0; h < 12; h++)
{
for (int m = 0; m < 60; m++)
{
if (__builtin_popcount(h) + __builtin_popcount(m) == turnedOn)
{
temp = "";
temp += to_string(h);
temp += ":";
if (m < 10)
temp += "0";
temp += to_string(m);
ans.push_back(temp);
}
}
}
return ans;
}
};
// @lc code=end
结果:
复杂度分析:
时间复杂度:O(1)
空间复杂度:O(1)