Skip to content

Instantly share code, notes, and snippets.

@zsolt-donca
Created February 16, 2017 11:32
Show Gist options
  • Save zsolt-donca/0555cb850864579fd245d46d7b95339f to your computer and use it in GitHub Desktop.
Save zsolt-donca/0555cb850864579fd245d46d7b95339f to your computer and use it in GitHub Desktop.
A scala solution to the binary watch problem: https://leetcode.com/problems/binary-watch/
object BinaryWatch extends App {
def hasBitCount(count: Int)(binTime: Int): Boolean = Integer.bitCount(binTime) == count
case class Time(hour: Int, minute: Int)
def parseTime(time: Int): Option[Time] = {
val hour = time >> 6
val minute = time & ((1 << 6) - 1)
if (hour < 12 && minute < 60)
Some(Time(hour, minute))
else
None
}
def formatTime(time: Time): String = f"${time.hour}:${time.minute}%02d"
// main function, as required by the problem
def readBinaryWatch(num: Int): List[String] = {
val maxBitCount = 10
val maxNum = (1 << maxBitCount) - 1
Stream.range(0, maxNum)
.filter(hasBitCount(num))
.flatMap(parseTime)
.map(formatTime)
.toList
}
for (i <- 0 to 10) {
val values = readBinaryWatch(i)
println(s"Watch faces with $i bits: $values")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment