Created
February 16, 2017 11:32
-
-
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/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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