Skip to content
This repository has been archived by the owner on Jul 10, 2024. It is now read-only.

added Find digital root of a number in Scala #5578

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import scala.annotation.tailrec

object findDigitalRootOfANumber {
def main(args: Array[String]): Unit = {
val number = 942
println(digitalRoot(number))
}

def sumOfDigits(n: Int): Int = {
if (n == 0) 0
else n % 10 + sumOfDigits(n / 10)
}

@tailrec
def digitalRoot(n: Int): Int = {
val sum = sumOfDigits(n)
if (sum < 10) sum
else digitalRoot(sum)
}
}