logo
logo

Reverse Integer

Lesson

Write a function to reverse the digits of an integer in JavaScript. You need to convert the integer to a string and then reverse it, and use some inbuilt methods for JavaScript from string manipulation and mathematical operations. The function should account for some constraints such as if the integer is negative or if it exceeds a certain value, in which case the function should return 0. Provide sample inputs and outputs to help the user better understand the question.

Sample Input: 12345
Sample Output: 54321

Sample Input: -12345
Sample Output: -54321

Sample Input: 190
Sample Output: 91

Walkthrough

To solve this question, we need to first get the absolute value of the input integer, so that we can work with it as a positive integer. We can then convert this absolute value to a string using the toString() method, and then split the string into an array of digits using the split() method. We can then reverse this array of digits using the reverse() method, and join it back into a string using the join() method.

After this, we can check the sign of the original input integer using the Math.sign() function, and multiply it with the reversed integer to get the output integer with the same sign as the input integer.

Finally, we need to check if the output integer is greater than 2^31, and if it is, return 0.

Here's the code for the solution:

function reverseDigits(input) {
  const absoluteValue = Math.abs(input);
  const arrayDigits = absoluteValue.toString().split("");
  const reversedArray = arrayDigits.reverse();
  const reversed = Number(reversedArray.join(""));
  const sign = Math.sign(input);

  if (reversed > 2 ** 31) {
    return 0;
  }

  return sign * reversed;
}

Big O Complexity Analysis: The time complexity of this solution is O(n), where n is the number of digits in the input integer, because we use several JavaScript methods with linear time complexity such as toString(), split(), reverse(), and join(). The space complexity of this solution is O(1), because we only use a constant amount of space to store the input integer, absolute value, array of digits, reversed array, reversed integer, and sign.