您的位置:首页 > 其它

Leetcode: 401. Binary Watch

2017-01-09 00:21 477 查看
这里我提出两种做法,一种呢就是把每个bit分开,这种写法很直接;一种是根据10bits的大小进行一次迭代,看哪些数字符合要求。

第一种方法:非常low

class Solution {
public:
vector<string> readBinaryWatch(int num) {
vector<string> result;

for(int h4 = 0; h4 <= 1; h4++)
for(int h3 = 0; h3 <= 1; h3++)
for(int h2 = 0; h2 <= 1; h2++)
for(int h1 = 0; h1 <= 1; h1++)
for(int m6 = 0; m6 <= 1; m6++)
for(int m5 = 0; m5 <= 1; m5++)
for(int m4 = 0; m4 <= 1; m4++)
for(int m3 = 0; m3 <= 1; m3++)
for(int m2 = 0; m2 <= 1; m2++)
for(int m1 = 0; m1 <= 1; m1++)
{
if(m1+m2+m3+m4+m5+m6+h1+h2+h3+h4 == num)
{
int h = h1 + (h2 << 1) + (h3 << 2) + (h4 << 3);
int m = m1+ (m2<<1)+(m3<<2)+(m4<<3) + (m5<<4) + (m6<<5);
if(h < 12 && m <= 59)
{
char str[20];
sprintf(str, "%d:%02d", h, m);
result.push_back(str);
}
}
}
return result;
}
};


第二种方法:好了一点点

class Solution {
public:
static int count_one_num(int tmp)
{
int rel = 0;

while(tmp)
{
rel += (tmp & 1);
tmp  = tmp >> 1;
}

return rel;
}

vector<string> readBinaryWatch(int num) {
vector<string> result;

int num_max = (11 << 6) | ((1 << 6) - 1);

for(int i = 0; i < num_max; i++)
{
int c = count_one_num(i);

if(c == num)
{
int h = i >> 6;
int m = i & 0x3f;

if(m <= 59)
{
char str[20];
sprintf(str, "%d:%02d", h, m);
result.push_back(str);
}
}
}

return result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 401 binary watch