Negative base numbers: Difference between revisions
Content added Content deleted
(→{{header|Go}}: More idiomatic error handling.) |
(Added Scala) |
||
Line 895: | Line 895: | ||
-6284695 converted to base -62 ────► Rexx |
-6284695 converted to base -62 ────► Rexx |
||
</pre> |
</pre> |
||
=={{header|Scala}}== |
|||
<lang scala>object NegativeBase { |
|||
val digits = ('0' to '9') ++ ('a' to 'z') ++ ('A' to 'Z') |
|||
def intToStr(n: Int, b: Int): String = { |
|||
def _fromInt(n: Int): List[Int] = { |
|||
if (n == 0) { |
|||
Nil |
|||
} else { |
|||
val r = n % b |
|||
val rp = if (r < 0) r + b else r |
|||
val m = -(n - rp)/b |
|||
rp :: _fromInt(m) |
|||
} |
|||
} |
|||
_fromInt(n).map(digits).reverse.mkString |
|||
} |
|||
def strToInt(s: String, b: Int): Int = { |
|||
s.map(digits.indexOf).foldRight((0, 1)){ case (x, (sum, pow)) => |
|||
(sum + x * pow, pow * -b) |
|||
}._1 |
|||
} |
|||
}</lang> |
|||
<lang scala>def testConversion(b: Int)(n: Int, s: String): Unit = { |
|||
println(s"$n in base -$b = ${NegativeBase.intToStr(n, b)}") |
|||
println(s"$s from base -$b = ${NegativeBase.strToInt(s, b)}") |
|||
} |
|||
testConversion(2)(10, "11110") |
|||
testConversion(3)(146, "21102") |
|||
testConversion(10)(15, "195") |
|||
testConversion(62)(795099356, "Scala")</lang> |
|||
{{out}} |
|||
<pre>10 in base -2 = 11110 |
|||
11110 from base -2 = 10 |
|||
146 in base -3 = 21102 |
|||
21102 from base -3 = 146 |
|||
15 in base -10 = 195 |
|||
195 from base -10 = 15 |
|||
795099356 in base -62 = Scala |
|||
Scala from base -62 = 795099356</pre> |
|||
=={{header|Sidef}}== |
=={{header|Sidef}}== |