Scala function: Calculate the sum of digits in a number
Write a Scala function to calculate the sum of digits in a given number.
Before you start!
To solve this problem, you should have a basic understanding of:
- Scala functions and how to define them.
- Loops (e.g., while loops) for iteration.
- Basic arithmetic operations, especially modulus (%) and division (/).
- How to extract digits from a number using modulus and integer division.
Try before looking at the solution!
Think about how you can break down a number into its individual digits:
- What operation gives you the last digit of a number?
- How do you remove the last digit from a number?
- How can you repeat this process until all digits are processed?
- What variable should you use to store the sum of the digits?
Try writing a small program to extract digits from a number before attempting the full solution!
Sample Solution:
Scala Code:
object DigitSumCalculator {
def sumOfDigits(n: Int): Int = {
var num = n
var sum = 0
while (num != 0) {
val digit = num % 10
sum += digit
num /= 10
}
sum
}
def main(args: Array[String]): Unit = {
val number = 12345678
val sum = sumOfDigits(number)
println(s"The sum of digits in $number is: $sum")
}
}
Sample Output:
The sum of digits in 12345678 is: 36
Scala Code Editor :
Previous: Determine if a number is prime.
Next: Reverse a Given String.
What is the difficulty level of this exercise?
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics