Login

Reverse an Integer

Write a function that reverses an integer.

Advanced


Instructions

Write a function that takes an integer as input and returns the integer reversed.

For example, if the input is 1234, the output should be 4321.

Tests
0/5
Function Call:
Expected:
reverseInteger(987)
789
Run test

reverseInteger(1234)
4321
Run test

Hidden Test
?
Run test

Hidden Test
?
Run test

Hidden Test
?
Run test

See Solution
const reverseInteger = (myInteger) => {
   const reversed =  parseInt(myInteger.toString().split('').reverse().join(''))
   return Math.sign(myInteger) * reversed
}

Explanation

The function takes an integer as an argument and converts it to a string. It then splits the string into an array of characters, reverses the array, and joins it back to a string. The string is then converted back to an integer. The function then multiplies the integer by the sign of the original integer to ensure that the result has the same sign as the original integer.

Complexity Analysis

The time complexity for this function is O(n) where n is the number of digits in the integer.

Alternatives

For loop

const reverseInteger = (myInteger) => {
      let reversed = 0
      while(myInteger !== 0){
         reversed = reversed * 10 + myInteger % 10
         myInteger = parseInt(myInteger / 10)
      }
      return reversed
   }

Lodash

import { reverse } from 'lodash'

const reverseInteger = (myInteger) => {
   return parseInt(reverse(myInteger.toString().split('')).join(''))
}

Any improvement idea? Share with us!