LeetCode: Reversing Integers with JavaScript

Hero image for LeetCode: Reversing Integers with JavaScript. Image by 愚木混株 cdd20.
Hero image for 'LeetCode: Reversing Integers with JavaScript.' Image by 愚木混株 cdd20.

For those of you who've been kneedeep in the world of web development, juggling with data types like integers might seem a bit rudimentary. After all, we're often more engrossed in CSS quirks, JavaScript frameworks, or responsive designs than we are concerned over basic numerals.

However, algorithms form the backbone of many operations we see on the web, whether it's search functionality, data sorting, or even some fancy animations. One such seemingly simple, yet intriguing problem is the 'Reverse Integer' problem.


Understanding the Problem

Imagine you've been given a 32bit integer, and your task is to reverse its digits, whilst returning a 32bit integer. Sounds simple enough, right? If you have the number 123, your function should return 321. For 123, the output should be 321.

However, the catch here is in dealing with the constraints and edge cases. What happens when the number is too large or too small? How do you efficiently handle negative numbers or zeroes at the end of the reversed integer? These nuances are what make the problem interesting and relevant, and can reveal more about your critical thinking and problemsolving in an interview environment than you might first think...

This type of task is crucial in web development, especially when dealing with data transformations, validations, or encryption mechanisms. Being confident in our ability to manipulate and transform basic data types is foundational for building robust web applications.

Constraints

  • The reversed integer should remain a 32bit integer.
  • If reversing the integer causes it to go out of the bounds of a 32bit signed integer, then return 0. The range of 32bit signed integers is from 2^31 to 2^311, or 2,147,483,648 to 2,147,483,647.


Key points

To solve this problem, you need to reverse the digits, not the whole number. For example, the reversed version of 123 is 321, not 321. Be mindful of integer overflow. If the reversed number doesn't fit within the 32bit integer range, return 0.


A Solution Using TypeScript and ES6

I tend to develop more or less entirely in TypeScript now, which takes away one of the issues this problem presents: incorrectlytyped inputs. Here, we're expecting the input to be a number.

function reverseInteger(x: number): number {  let reversed: number = 0;  while (x !== 0) {    reversed = reversed * 10 + (x % 10);    x = Math.trunc(x / 10);  }  // Checking for integer overflow  if (reversed < (-2) ** 31 || reversed > 2 ** 31 - 1) {    return 0;  }  return reversed;}

How It Works

  1. We initialise a variable reversed to store our reversed number.
  2. The while loop is used to reverse the digits of the number.
  3. We then multiply the reversed number by 10 and add the last digit of the original number to it.
  4. The original number is then divided by 10 (using truncation to discard the decimal part).
  5. We iterate through this loop until the original number becomes zero.
  6. Finally, there's a check to ensure our reversed number doesn't overflow the 32bit integer limit. If it does, we return 0.

Another Approach

Above, I've focused on a mathematical solution: manipulating the numbers to produce the desired output. There is another option that will achieve just the same result with a little more type manipulation.

The Code

const reverse = (x: number): number => {  // Convert the number to string, reverse it, and parse it back to an integer  let reversed: number = parseInt(    Math.abs(x).toString().split('').reverse().join('')  );  // If the input number was negative, make the reversed number negative  if (x < 0) {    reversed = -reversed;  }  // Check for 32-bit signed integer boundaries  const INT_MIN: number = (-2) ** 31;  const INT_MAX: number = 2 ** 31 - 1;  if (reversed < INT_MIN || reversed > INT_MAX) {    return 0;  }  return reversed;};

How It Works

  1. Convert to String and Reverse:

    Since JavaScript does not have a direct way to reverse numbers, you can convert the number to a string, then to an array, then reverse the array, and finally, join it back together to get a reversed string.
  2. Check Negative Numbers:

    If the input number is negative, handle it appropriately.
  3. Boundaries Check:

    Ensure that the reversed number is within the 32bit signed integer range.

It's worth noting that I'm using Math.pow to calculate the power of 2. I feel that in many practical scenarios, the 32bit integer limits will be provided to you, or they could even be hardcoded, rather than needing to be calculated every time the function is called.

Overall, this is perhaps a simpler and easiertounderstand solution, although it won't be as performant when it comes to dealing with larger inputs.


Wrapping up

Algorithms, even as fundamental as reversing an integer, play a vital role in the world of web development. They strengthen our problemsolving muscles and better prepare us to tackle more complex challenges on the web.


Categories:

  1. Algorithms
  2. Guides
  3. JavaScript
  4. LeetCode
  5. TypeScript