Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.
Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.
Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
This is a widely used question in programming competitions. Most instructors will give you this kind of questions in classrooms too.
Here's a solution to reverse an integer in C++ without using 64-bit integers:
class Solution {
public:
int reverse(int x) {
int result = 0;
while (x != 0) {
int tail = x % 10;
int newResult = result * 10 + tail;
if ((newResult - tail) / 10 != result) {
return 0;
}
result = newResult;
x = x / 10;
}
return result;
}
};
Explanation:
- First, we initialize the result variable to 0.
- In the while loop, we extract the last digit of x by taking the modulo 10 of x.
- Then, we add this digit to the current result by multiplying the result by 10 and adding the extracted digit.
- Before updating the result, we check if the reversed integer would go outside the signed 32-bit range. We do this by checking if (newResult - tail) / 10 is equal to the original result. If not, we return 0.
- Finally, we divide x by 10 to remove the last digit and repeat the process until x becomes 0.
Comments
Post a Comment