Search code examples
stringscalaintegerreverse

Is there a more efficient way to reverse a integer number (both positive and negative) in SCALA?


I am making a program in SCALA that takes a integer number and reverses it. For example, an input of 30 returns an output of 3. This program must also work for negative numbers, For instance, an input of -89 returns an output of -98. Also, if in the reversal the first digit is 0, it should be truncated (30 to 3). This is the code I have written.

import io.StdIn._

val twoDigitNumber : Int = takeInput()
println("The reversal is " + reverse(twoDigitNumber))

//define a function name reverse to handle the actual reverse process for -ve and +ve numbers
 def reverse(x: Integer): Integer = {

 //4 possibilities: +ve, 1st digit 0; -ve, 1st digit zero; -ve, 1st digit not zero; +ve, 1st digit not zero
 if (x> 0 && x.toString.reverse.charAt(0) == 0) {
    x.toString.reverse.substring(1).toInt
 } else if (x<0 && x.toString.substring(1).reverse.charAt(0) == 0) {
  ('-' + x.toString.substring(1).reverse.substring(1)).toInt
 } else if (x<0 && x.toString.substring(1).reverse.charAt(0)!= 0) {
  ('-'+ x.toString.substring(1).reverse).toInt
 } else {
  x.toString.reverse.toInt
 }
}

//reads an integer number
def takeInput() : Int ={
 print("Enter a two-digit integer number: ")
 readInt()
}

Is there a more efficient way to do this?


Solution

  • The shortest I found:

    x.signum * x.abs.toString.reverse.toInt