A binary watch has 4 LEDs on the top which represent the hours (0-11), and the 6 LEDs on the bottom represent the minutes (0-59).
Each LED represents a zero or one, with the least significant bit on the right.
For example, the above binary watch reads "3:25".
Given a non-negative integer n which represents the number of LEDs that are currently on, return all possible times the watch could represent.
Example:
Input: n = 1
Return: ["1:00", "2:00", "4:00", "8:00", "0:01", "0:02", "0:04", "0:08", "0:16", "0:32"]
這是一道很簡單的題,基本上就是十進制和二進制的轉換而已。但是讓我意識到自己還有很多知識的盲區。
這是我寫的Accepted代碼,真的是搓到不行:
class Solution {
public:
vector<pair<int,int>> hour;
vector<pair<int,int>> minute;
void initAll()
{
for(int i=0;i<12;i++)
{
int cur=i,temp=0;
while(cur>0)
{
if(cur%2==1)temp++;
cur/=2;
}
hour.push_back(make_pair(i,temp));
}
for(int i=0;i<60;i++)
{
int cur=i,temp=0;
while(cur>0)
{
if(cur%2==1)temp++;
cur/=2;
}
minute.push_back(make_pair(i,temp));
}
}
vector<int> getHour(int num)
{
vector<int> temp;
for(vector<pair<int,int>>::iterator iter=hour.begin();iter!=hour.end();iter++)
{
pair<int,int> tempPair=*iter;
if(tempPair.second==num)temp.push_back(tempPair.first);
}
return temp;
}
vector<int> getMinute(int num)
{
vector<int> temp;
for(vector<pair<int,int>>::iterator iter=minute.begin();iter!=minute.end();iter++)
{
pair<int,int> tempPair=*iter;
if(tempPair.second==num)temp.push_back(tempPair.first);
}
return temp;
}
vector<string> readBinaryWatch(int num) {
initAll();
vector<string> ans;
for(int i=0;i<=num;i++)
{
int j=num-i;
if(i>4||j>6)continue;
vector<int> tempHour=getHour(i);
vector<int> tempMinute=getMinute(j);
int len1=tempHour.size();
int len2=tempMinute.size();
for(int p=0;p<len1;p++)
{
for(int q=0;q<len2;q++)
{
string tempans=to_string(tempHour[p]);
tempans+=":";
if(tempMinute[q]<=9)tempans+="0";
tempans+=to_string(tempMinute[q]);
ans.push_back(tempans);
}
}
}
return ans;
}
};
然後這是看到的別的大佬寫的:
class Solution {
public:
vector<string> readBinaryWatch(int num) {
vector<string> rs;
for (int h = 0; h < 12; h++)
for (int m = 0; m < 60; m++)
if (bitset<10>(h << 6 | m).count() == num)
rs.emplace_back(to_string(h) + (m < 10 ? ":0" : ":") + to_string(m));
return rs;
}
};
你們感受一下這兩份代碼的差距......
我只能說,bitset真乃神器也。路漫漫其修遠兮,吾將上下而求索。