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 , which is equal to . The max value is , which is equal to . 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 , the output should be . If the input is , the output should be . If the input is , the output should be because the reversed integer is , which is larger than .
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 . This means that the result cannot be less than or greater than . If the result goes beyond this range, the function should return 0.
INT_MAX / 10
, then adding any digit will cause overflow.INT_MAX / 10
, then adding a digit greater than will cause overflow.INT_MIN / 10
, then adding any digit will cause underflow.INT_MIN / 10
, then adding a digit less than will cause underflow.