Sha256: 022f5728b6ebc3142af29de612710290740ad4ba970f5f4be0b1df8a32ab5c0b

Contents?: true

Size: 835 Bytes

Versions: 396

Compression:

Stored size: 835 Bytes

Contents

import scala.annotation.tailrec

object Octal {
  def octalToInt(s: String): Int = {
    if (s.isEmpty) throw new IllegalArgumentException("Invalid Octal")

    s.foldLeft(0){case (acc, c) => accumulate(acc, c)}
  }

  private def accumulate(acc: Int, c: Char) = {
    if (!c.isDigit || c.asDigit < 0 || c.asDigit > 7)
      throw new IllegalArgumentException("Invalid Octal Char - " + c)

    c.asDigit + (acc * 8)
  }

  def intToOctal(n: Int): String = {
    if (n < 0) throw new IllegalArgumentException("Only positive numbers supported")

    @tailrec
    def intToOct(n: Int, acc: String): String = {
      val octalChar = ((n % 8) + '0').toChar
      val accum = octalChar + acc

      n match {
        case 0 => if (acc.isEmpty) accum else acc
        case _ => intToOct(n / 8, accum)
      }
    }

    intToOct(n, "")
  }
}

Version data entries

396 entries across 396 versions & 1 rubygems

Version Path
trackler-2.2.1.119 tracks/scala/exercises/octal/example.scala
trackler-2.2.1.118 tracks/scala/exercises/octal/example.scala
trackler-2.2.1.117 tracks/scala/exercises/octal/example.scala
trackler-2.2.1.116 tracks/scala/exercises/octal/example.scala
trackler-2.2.1.115 tracks/scala/exercises/octal/example.scala
trackler-2.2.1.114 tracks/scala/exercises/octal/example.scala
trackler-2.2.1.113 tracks/scala/exercises/octal/example.scala
trackler-2.2.1.111 tracks/scala/exercises/octal/example.scala
trackler-2.2.1.110 tracks/scala/exercises/octal/example.scala
trackler-2.2.1.109 tracks/scala/exercises/octal/example.scala
trackler-2.2.1.108 tracks/scala/exercises/octal/example.scala
trackler-2.2.1.107 tracks/scala/exercises/octal/example.scala
trackler-2.2.1.106 tracks/scala/exercises/octal/example.scala
trackler-2.2.1.105 tracks/scala/exercises/octal/example.scala
trackler-2.2.1.104 tracks/scala/exercises/octal/example.scala
trackler-2.2.1.103 tracks/scala/exercises/octal/example.scala
trackler-2.2.1.102 tracks/scala/exercises/octal/example.scala
trackler-2.2.1.101 tracks/scala/exercises/octal/example.scala
trackler-2.2.1.100 tracks/scala/exercises/octal/example.scala
trackler-2.2.1.99 tracks/scala/exercises/octal/example.scala