How to extract the last N digits from a number in Scala

1 Answer

0 votes
object LastNDigitsApp {

  /*
      Extracts the last N digits from a given number.

      Approach:
        - To get the last N digits, compute: number % math.pow(10, digits).toInt
        - This avoids string manipulation and uses efficient arithmetic.

      Parameters:
        number : the original integer
        digits : how many digits to extract from the end

      Returns:
        The last N digits as an Int.
  */
  def getLastNDigits(number: Int, digits: Int): Int = {
    // Compute 10^digits using math.pow (returns Double)
    // Convert to Int because modulo requires integer operands
    val divisor: Int = math.pow(10, digits).toInt

    // Modulo returns the remainder, which is exactly the last N digits
    number % divisor
  }

  def main(args: Array[String]): Unit = {
    // Example values
    val number: Int = 987654321
    val digits: Int = 4

    // Extract the last N digits
    val result: Int = getLastNDigits(number, digits)

    // Display the result
    println(s"Original number: $number")
    println(s"Digits requested: $digits")
    println(s"Last $digits digits: $result")
  }
}


/*
run:

Original number: 987654321
Digits requested: 4
Last 4 digits: 4321

*/

 



answered Sep 18 by avibootz
...