Integer Reversal

Integer Reversal

Given a integer, return an integer that is the reverse ordering of numbers

// reverseInt(15) === 51
// reverseInt(981) === 189
// reverseInt(500) === 5
// reverseInt(-15) === -51
// reverseInt(-90) === -9

Reversing a integer can be done in a similar way to reversing a string. Firstly we need to convert the integer to a string. Once converted we can reverse the string and then convert the reversed string back to a integer. If the original integer was negative this will remove the trailing "-". So we need to check if the original integer is negative, if so convert the reversed number to a negative integer

Solution

  1. Convert the integer to a string
  2. Split the string
  3. Reverse the string
  4. Join the string back together
  5. Convert the reversed string back to a integer with parseInt() - this will remove the trailing "-" on negative cases
  6. Check if the original integer is negative. If so return the reversed number and convert to a negative number. If original integer is positive return the reversed number
const reverseInt = (number) => {
const reversed = parseInt(number.toString().split('').reverse().join(''))
  return number < 0 ? reversed * -1 : reversed
}

Instead of doing the final check we can use the built in Math.sign() function that returns 1 if the number is positive or -1 if the number is negative. We are able to return the reversed string and * Math.sign(number)

Math.sign(500) // 1
math.sign(-500) //-1
const reverseInt = (number) => {
  const reversed = parseInt(number.toString().split('').reverse().join(''))
  // return number < 0 ? reversed * -1 : reversed
  return reversed * Math.sign(number)
}