/**
* Problem: LeetCode 401 - Binary Watch
* Difficulty: Easy
* Language: Java
* Author: CodeByTushu
*/
import java.util.ArrayList;
import java.util.List;
class Solution {
public List<String> readBinaryWatch(int turnedOn) {
List<String> result = new ArrayList<>();
if (turnedOn < 0 || turnedOn > 8) {
return result;
}
for (int h = 0; h < 12; h++) {
for (int m = 0; m < 60; m++) {
if (Integer.bitCount(h) + Integer.bitCount(m) == turnedOn) {
result.add(String.format("%d:%02d", h, m));
}
}
}
return result;
}
}
"""
Problem: LeetCode 401 - Binary Watch
Difficulty: Easy
Language: Python
Author: CodeByTushu
"""
from typing import List
class Solution:
def readBinaryWatch(self, turnedOn: int) -> List[str]:
if turnedOn < 0 or turnedOn > 8:
return []
result = []
for h in range(12):
for m in range(60):
if (bin(h).count('1') + bin(m).count('1')) == turnedOn:
result.append(f"{h}:{m:02d}")
return result
/**
* Problem: LeetCode 401 - Binary Watch
* Difficulty: Easy
* Language: C++
* Author: CodeByTushu
*/
#include <vector>
#include <string>
using namespace std;
class Solution {
public:
vector<string> readBinaryWatch(int turnedOn) {
vector<string> result;
if (turnedOn < 0 || turnedOn > 8) {
return result;
}
for (int h = 0; h < 12; h++) {
for (int m = 0; m < 60; m++) {
if (__builtin_popcount(h) + __builtin_popcount(m) == turnedOn) {
string time = to_string(h) + ":" + (m < 10 ? "0" : "") + to_string(m);
result.push_back(time);
}
}
}
return result;
}
};
/**
* Problem: LeetCode 401 - Binary Watch
* Difficulty: Easy
* Language: JavaScript
* Author: CodeByTushu
*/
/**
* @param {number} turnedOn
* @return {string[]}
*/
var readBinaryWatch = function(turnedOn) {
if (turnedOn < 0 || turnedOn > 8) {
return [];
}
const result = [];
const countBits = (n) => {
let count = 0;
while (n > 0) {
count += n & 1;
n >>= 1;
}
return count;
};
for (let h = 0; h < 12; h++) {
for (let m = 0; m < 60; m++) {
if (countBits(h) + countBits(m) === turnedOn) {
result.push(`${h}:${m < 10 ? '0' : ''}${m}`);
}
}
}
return result;
};