Isaac Emmanuel
15 Jun 2024•EasyC++ / Python / TypeScript

Binary Watch

C++, Python and TypeScript solutions for Binary Watch.

The Binary Watch solutions are below.

Solution files

Python•binary-watch/synced-solution.py
def readBinaryWatch(num):
    result = []

    for h in range(12):
        for m in range(60):
            if bin(h).count('1') + bin(m).count('1') == num:
                result.append(f"{h}:{m:02d}")

    return result
C++•binary-watch/synced-solution.cpp
class Solution {
public:
    vector<string> readBinaryWatch(int num) {
        vector<string> result;

        for (int h = 0; h < 12; h++) {
            for (int m = 0; m < 60; m++) {
                if (__builtin_popcount(h) + __builtin_popcount(m) == num) {
                    char time[6];
                    sprintf(time, "%d:%02d", h, m);
                    result.push_back(string(time));
                }
            }
        }

        return result;
    }
};
TypeScript•binary-watch/synced-solution.ts
function readBinaryWatch(num: number): string[] {
    const result: string[] = [];

    for (let h = 0; h < 12; h++) {
        for (let m = 0; m < 60; m++) {
            const bitCount = (h.toString(2).match(/1/g) || []).length +
                           (m.toString(2).match(/1/g) || []).length;
            if (bitCount === num) {
                result.push(`${h}:${String(m).padStart(2, '0')}`);
            }
        }
    }

    return result;
}