Skip to content

Instantly share code, notes, and snippets.

@MishaelRosenthal
Created October 29, 2022 04:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MishaelRosenthal/376577b21ce1d8210b728e2c9f82be49 to your computer and use it in GitHub Desktop.
Save MishaelRosenthal/376577b21ce1d8210b728e2c9f82be49 to your computer and use it in GitHub Desktop.
type Digit = Int
def toDigits(i: Int) = i.toString.map(_.asDigit).reverse
def fromDigits(digits: Seq[Digit]) = digits.reverse.dropWhile(_ == 0).map(_.toString).reduce(_ + _).toInt
case class FullAdder(inCarry: Digit, i: Digit, j: Digit) {
val asDigits = toDigits(inCarry + i + j)
def sum() = asDigits(0)
def carry() = if(asDigits.length > 1) asDigits(1) else 0
}
def longAddition(x: Int, y: Int) = {
val xDigits = toDigits(x) ++ Seq(0)
val yDigits = toDigits(y) ++ Seq(0)
val zipped = xDigits.zipAll(yDigits, 0, 0)
val adders = zipped.scanLeft(FullAdder(0, 0, 0)) { case (acc, (i, j)) => FullAdder(acc.carry(), i, j)}.tail
fromDigits(adders.map(_.sum()))
}
val x = 145678
val y = 7865
val res = longAddition(x, y)
println("res is " + res + ", res equals x + y is " + (x + y == res))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment