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.180 tracks/scala/exercises/octal/example.scala
trackler-2.2.1.179 tracks/scala/exercises/octal/example.scala
trackler-2.2.1.178 tracks/scala/exercises/octal/example.scala
trackler-2.2.1.177 tracks/scala/exercises/octal/example.scala
trackler-2.2.1.176 tracks/scala/exercises/octal/example.scala
trackler-2.2.1.175 tracks/scala/exercises/octal/example.scala
trackler-2.2.1.174 tracks/scala/exercises/octal/example.scala
trackler-2.2.1.173 tracks/scala/exercises/octal/example.scala
trackler-2.2.1.172 tracks/scala/exercises/octal/example.scala
trackler-2.2.1.171 tracks/scala/exercises/octal/example.scala
trackler-2.2.1.170 tracks/scala/exercises/octal/example.scala
trackler-2.2.1.169 tracks/scala/exercises/octal/example.scala
trackler-2.2.1.167 tracks/scala/exercises/octal/example.scala
trackler-2.2.1.166 tracks/scala/exercises/octal/example.scala
trackler-2.2.1.165 tracks/scala/exercises/octal/example.scala
trackler-2.2.1.164 tracks/scala/exercises/octal/example.scala
trackler-2.2.1.163 tracks/scala/exercises/octal/example.scala
trackler-2.2.1.162 tracks/scala/exercises/octal/example.scala
trackler-2.2.1.161 tracks/scala/exercises/octal/example.scala
trackler-2.2.1.160 tracks/scala/exercises/octal/example.scala