Binary Watch

easy bit manipulation backtracking

Problem

A binary watch shows hours (0–11) and minutes (0–59) by LEDs in binary. Given the number of LEDs on, return all valid times "H:MM".

InputturnedOn = 1
Output["0:01","0:02","0:04","0:08","0:16","0:32","1:00","2:00","4:00","8:00"]
One LED total — either one of the six minute bits or four hour bits.

def read_binary_watch(turned_on):
    out = []
    for h in range(12):
        for m in range(60):
            if bin(h).count("1") + bin(m).count("1") == turned_on:
                out.append(f"{h}:{m:02d}")
    return out
function readBinaryWatch(turnedOn) {
  const out = [];
  const pop = x => { let c = 0; while (x) { c += x & 1; x >>= 1; } return c; };
  for (let h = 0; h < 12; h++) {
    for (let m = 0; m < 60; m++) {
      if (pop(h) + pop(m) === turnedOn) out.push(h + ":" + String(m).padStart(2, "0"));
    }
  }
  return out;
}
class Solution {
    public List readBinaryWatch(int turnedOn) {
        List out = new ArrayList<>();
        for (int h = 0; h < 12; h++)
            for (int m = 0; m < 60; m++)
                if (Integer.bitCount(h) + Integer.bitCount(m) == turnedOn)
                    out.add(String.format("%d:%02d", h, m));
        return out;
    }
}
vector readBinaryWatch(int turnedOn) {
    vector out;
    for (int h = 0; h < 12; h++)
        for (int m = 0; m < 60; m++)
            if (__builtin_popcount(h) + __builtin_popcount(m) == turnedOn) {
                char buf[8]; snprintf(buf, 8, "%d:%02d", h, m);
                out.push_back(buf);
            }
    return out;
}
Time: O(1) Space: O(1)