Reverse Integer

Sep 24, 2023#leetcode#dsa

The Reverse Integer problem on LeetCode is a coding challenge that asks you to reverse the digits of a given 32-bit integer and return the reversed integer. If the reversed integer is out of the range of 32-bit integers, you should return 0.

For a signed 32-bit integer, the min value is βˆ’231-2^{31}, which is equal to βˆ’2147483648-2147483648. The max value is 231βˆ’12^{31} - 1, which is equal to 21474836472147483647. This is because the most significant bit (the leftmost bit) is used to indicate the sign of the number, leaving 31 bits to store the magnitude.

For example, if the input is 123123, the output should be 321321. If the input is βˆ’120-120, the output should be βˆ’21-21. If the input is 15342364691534236469, the output should be 00 because the reversed integer is 96463243519646324351, which is larger than 231βˆ’12^{31} - 1.

Here’s solution in C++:

#include <cassert>
#include <climits> // INT_MAX, INT_MIN
#include <iostream>

using namespace std;

int reverse(int x) {
  int reversed = 0;

  while (x != 0) {
    int pop = x % 10;
    x /= 10;

    if (reversed > INT_MAX / 10 || (reversed == INT_MAX / 10 && pop > 7)) {
      return 0;
    }
    if (reversed < INT_MIN / 10 || (reversed == INT_MIN / 10 && pop < -8)) {
      return 0;
    }

    reversed = reversed * 10 + pop;
  }

  return reversed;
}

int main() {
  assert(reverse(12345) == 54321);
  assert(reverse(-54321) == -12345);
  assert(reverse(1534236469) == 0); // overflow
  cout << "All test cases passed!" << endl;
  return 0;
}

The step of checking overflow is to prevent the result from exceeding the range of a signed 32-bit integer, which is [βˆ’231,231βˆ’1][-2^{31}, 2^{31} - 1]. This means that the result cannot be less than βˆ’231-2^{31} or greater than 231βˆ’12^{31} - 1. If the result goes beyond this range, the function should return 0.

  • If the result is greater than INT_MAX / 10, then adding any digit will cause overflow.
  • If the result is equal to INT_MAX / 10, then adding a digit greater than 77 will cause overflow.
  • If the result is less than INT_MIN / 10, then adding any digit will cause underflow.
  • If the result is equal to INT_MIN / 10, then adding a digit less than βˆ’8-8 will cause underflow.