Binary Watch

As I’ve mentioned before, I really enjoy solving problems involving bit manipulation and this is one of the many problems that are fun to solve with.

class Solution {
    fun readBinaryWatch(num: Int): List<String> {
        val times = mutableListOf<String>()
        (0..11).forEach { hour ->
            val hourBits = Integer.bitCount(hour)
			
			// for every possible hours
            if(hourBits <= num) {
				// find out every possible minutes
                (0..59).forEach { minute ->
                    val minBits = Integer.bitCount(minute)
					
					// num - hourBits calculates the remaining LEDs that can be turned on for the minute LEDs
                    if(minBits == num - hourBits) {
                        times.add("$hour:${if(minute < 10) "0$minute" else minute}")    
                    }                
                }    
            }
        }
        
        return times.toList()
    }
}
Runtime: 152 ms, faster than 100.00% of Kotlin online submissions for Binary Watch.
Memory Usage: 33.5 MB, less than 100.00% of Kotlin online submissions for Binary Watch.

Time complexity is O( 12 x 60 ) or O(1)