I decided to use NAND instead of NOR, but it’s effectively the same thing.
Scala:
//main
@main
def main(): Unit =
var i = 15 //Choose any number here
i = add(i, 1) //this increments i
println(i)
//Adds 2 numbers in the most intuitive way
def add(a: Int, b: Int): Int =
val pairs = split(a).zip(split(b))
val sumCarry = pairs.scanLeft(false, false)((last, current) => fullAdder(current._1, current._2, last._2))
return join(sumCarry.map(_._1).tail.reverse)
//Converts an integer to a list of booleans
def join(list: Seq[Boolean]): Int = BigInt(list.map(if (_) '1' else '0').mkString, 2).toInt
//Converts a list of booleans to an integer
def split(num: Int): Seq[Boolean] = num.toBinaryString.reverse.padTo(32, '0').map(_ == '1')
//Adds 2 booleans and a carry in, returns a sum and carry out
def fullAdder (a: Boolean, b: Boolean, c: Boolean): (Boolean, Boolean) =
(NAND(NAND(NAND(NAND(a, NAND(a, b)), NAND(NAND(a, b), b)), NAND(NAND(NAND(a, NAND(a, b)), NAND(NAND(a, b), b)), c)), NAND(NAND(NAND(NAND(a, NAND(a, b)), NAND(NAND(a, b), b)), c), c)), NAND(NAND(NAND(NAND(a, NAND(a, b)), NAND(NAND(a, b), b)), c), NAND(a, b)))
//The basis for all operations
def NAND(a: Boolean, b: Boolean): Boolean = !a || !b
EDIT: replaced Integer.parseInt with BigInt(...).toInt to fix NumberFormatException with negative numbers.
I decided to use NAND instead of NOR, but it’s effectively the same thing.
Scala:
EDIT: replaced
Integer.parseInt
withBigInt(...).toInt
to fixNumberFormatException
with negative numbers.try it online here