Balanced ternary: Difference between revisions

→‎{{header|Kotlin}}: Updated example see https://github.com/dkandalov/rosettacode-kotlin for details
(Added Kotlin)
(→‎{{header|Kotlin}}: Updated example see https://github.com/dkandalov/rosettacode-kotlin for details)
Line 2,558:
import java.math.BigInteger
 
val bigZero = BigInteger.ZERO
val bigOne = BigInteger.ONE
val bigThree = BigInteger.valueOf(3L)
 
data class BTernary(private var value: String) : Comparable<BTernary> {
 
init {
require(value.all { it in "0+-" } )
value = value.trimStart('0')
}
 
constructor(v: Int) : this(BigInteger.valueOf(v.toLong()))
 
constructor(v: LongBigInteger) : this(BigInteger.valueOf(v)"") {
value = toBT(v)
 
constructor(v: BigInteger): this("") {
value = toBT(v)
}
 
private fun toBT(v: BigInteger): String {
if (v < bigZero) return flip(toBT(-v))
Line 2,632 ⟶ 2,630:
}
 
private fun addDigits(a: Char, b: Char): String =
when {
a == '0' -> b.toString()
Line 2,643 ⟶ 2,641:
var a = this.value
var b = other.value
val longer = if (a.length > b.length) a else b
var shorter = if (a.length > b.length) b else a
while (shorter.length < longer.length) shorter = "0" + shorter
Line 2,661 ⟶ 2,659:
 
operator fun unaryMinus() = BTernary(flip(this.value))
 
operator fun minus(other: BTernary) = this + (-other)
 
operator fun times(other: BTernary): BTernary {
var that = other
val one = BTernary(1)
val zero = BTernary(0)
var mul = zero
var flipFlag = false
if (that < zero) {
Line 2,681 ⟶ 2,679:
if (flipFlag) mul = -mul
return mul
}
 
override operator fun equalscompareTo(other: BTernary) = this.compareTo(other) == 0
 
override operator fun compareTo(other: BTernary) =
this.toBigInteger().compareTo(other.toBigInteger())
 
override fun toString() = value
}
 
Line 2,697 ⟶ 2,693:
println("a = ${a.toBigInteger()}")
println("b = ${b.toBigInteger()}")
println("c = ${c.toBigInteger()}")
val bResult = a * (b - c)
val iResult = bResult.toBigInteger()
println("a * (b - c) = $bResult = $iResult")
}</lang>