src/main/scala/binary.scala

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
object Binary {
  def apply(digits: String) = new Binary(digits)

  val ValidDigits = "([01]*)".r
}

class Binary(input: String) {
  private def decodeBinary(digits: String) =
    digits.foldLeft(0) {
      (acc, digit) => acc * 2 + digit.asDigit
    }

  lazy val toDecimal = input match {
    case Binary.ValidDigits(digits) => decodeBinary(digits)
    case _ => 0
  }
}

@abo64 thinks this looks great

Comments

Much nicer way to solve the problem (in any language)!

helenst commented 13 May 2016 at 08:44 UTC

exactly! :-)

abo64 commented 13 May 2016 at 10:13 UTC

You're not logged in right now. Please login via GitHub to comment