// challenge 305 Easy Permutation Base
// https://w...content-available-to-author-only...t.com/r/dailyprogrammer/comments/5xu7sz/20170306_challenge_305_easy_permutation_base/
//package challenge._305_easy
import java.math.BigInteger
fun toBinary(dec: String): String {
var sb = StringBuilder()
var v: BigInteger = BigInteger(dec)
var n: BigInteger = BigInteger.valueOf(1)
var bits: Int = 1
val two: BigInteger = BigInteger.valueOf(2)
while (true) {
val nextN = n.multiply(two)
if (v.compareTo(nextN) >= 0) {
v = v.minus(nextN)
n = nextN
bits++
} else {
break
}
}
while (bits > 0) {
val rem = v.remainder(two)
sb.append(rem.toString())
v = v.divide(two)
bits--
}
sb = sb.reverse()
println("$dec -> ${sb.toString()}")
return sb.toString()
}
fun toDecimal(bin: String): String {
var v = BigInteger.ZERO
var two = BigInteger.valueOf(2)
for (i in 0..bin.length-1) {
v = v.multiply(two) + BigInteger(bin[i].toString())
}
var offset = BigInteger.ZERO
var n = BigInteger.valueOf(1)
var bits = bin.length-1
for (i in 1..bits) {
n = n.multiply(two)
offset = offset.add(n)
}
v = v.add(offset)
println("$bin -> $v")
return v.toString()
}
fun main(args: Array<String>) {
toDecimal(toBinary("54"))
toBinary(toDecimal("111000111"))
toDecimal(toBinary("234234234"))
toDecimal(toBinary("234234234234234"))
toDecimal(toBinary("234234234234234234234234"))
toBinary(toDecimal("000111000111111000111111000111111000111"))
toBinary(toDecimal("11111111000111000111111000111111000111111000111"))
}