Input: n = 1
Return: ["1:00", "2:00", "4:00", "8:00", "0:01", "0:02", "0:04", "0:08", "0:16", "0:32"] class Solution {
public List<String> readBinaryWatch(int num) {
List<String> res = new ArrayList<>();
for (int hour = 0; hour < 12; ++hour) {
for (int minute = 0; minute < 60; ++minute) {
int bitNum = countBits(hour) + countBits(minute);
if (bitNum == num) {
res.add(String.format("%d:%02d", hour, minute));
}
}
}
return res;
}
private int countBits(int n) {
int ret = 0;
while (n > 0) {
ret += n & 1;
n >>>= 1;
}
return ret;
}
} class Solution {
public:
vector<string> readBinaryWatch(int num) {
vector<string> res;
for (int h = 0; h < 12; ++h) {
for (int m = 0; m < 60; ++m) {
if (countBit(h) + countBit(m) == num) {
char buffer[20];
sprintf(buffer, "%d:%02d", h, m);
res.push_back(string(buffer));
}
}
}
return res;
}
int countBit(int num) {
int ret = 0;
while (num > 0) {
ret += num & 1;
num >>= 1;
}
return ret;
}
};