Data commit
This commit is contained in:
parent
7387c8f97b
commit
cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions
|
|
@ -0,0 +1,23 @@
|
|||
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
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
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")
|
||||
Loading…
Add table
Add a link
Reference in a new issue