Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Created by Roman on 18.03.17.
- */
- class Binary private (n: Int, l:List[Int]) {
- private val container: List[Int] = if (l == Nil) this.construct(List[Int](), n) else l
- private val sum:(List[Int], List[Int], List[Int], Int) => List[Int] = {
- case (Nil, Nil, res, 0) => res
- case (Nil, Nil, res, r) => r%2::res
- case (x::a, Nil, res, r) => sum(a, Nil, (x+r)%2::res, (x+r)/2)
- case (Nil, x::b, res, r) => sum(Nil, b, (x+r)%2::res, (x+r)/2)
- case (x1::a, x2::b, res, r) => sum(a, b, (x1+x2+r)%2::res, (x1+x2+r)/2)
- }
- private def construct(l:List[Int], n:Int): List[Int] = (l, n) match {
- case (_, 0) => l
- case (l:List[Int], n:Int) => construct((n & 1)::l, n >> 1)
- }
- private def this(container:List[Int]) = {
- this(0, container)
- }
- def this(n:Int) = {
- this(n, Nil)
- }
- def + (o: Binary): Binary = {
- new Binary(this.sum(this.container.reverse, o.container.reverse, List[Int](), 0))
- }
- def << (n: Int): Binary = {
- new Binary(this.container:::List.fill(n)(0))
- }
- def * (o: Binary): Binary = {
- this.container.reverse.zipWithIndex.foldLeft(new Binary(0)) { (prod:Binary, z:(Int, Int)) => {
- if (z._1 == 1) prod + (o << z._2) else prod
- }}
- }
- def intValue:Int = {
- this.container.reverse.zipWithIndex.foldLeft(0) { (s:Int, z:(Int, Int)) => s + (z._1 * (1 << z._2))}
- }
- }
- object Main {
- def main(args: Array[String]): Unit = {
- val a = new Binary(12)
- val b = new Binary(12)
- val c = a * b
- print(c.intValue)
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement