less than 1 minute read

Problem Statement

leetcode problem link

Python Solution


class Solution:
    def readBinaryWatch(self, turnedOn: int) -> List[str]:
        res = []
        for h in range(12):
            for m in range(60):
                if bin(h).count("1") + bin(m).count("1") == turnedOn:
                    res.append(f"{h}:{m:02d}")

        return res

C# solution

using System;
using System.Collections.Generic;
using System.Numerics;

public class Solution {
    public IList<string> ReadBinaryWatch(int turnedOn) {
        var res = new List<string>();

        for (int h = 0; h < 12; h++) {
            for (int m = 0; m < 60; m++) {
                // Count bits using BitOperations.PopCount (C# 13 / .NET 9)
                if (BitOperations.PopCount((uint)h) + BitOperations.PopCount((uint)m) == turnedOn) {
                    res.Add($"{h}:{m:D2}");  // D2 ensures two-digit formatting for minutes
                }
            }
        }

        return res;
    }
}