In the Leetcode Reverse Integer problem solution in C++ programming 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).
Leetcode Reverse Integer problem solution in C++ programming
class Solution {
public:
int reverse(int x) {
int poflow = INT_MAX/10, poflowd = INT_MAX%10, noflow = INT_MIN/10, noflowd = INT_MIN%10;
int ans = 0, d = 0;
while(x){
d = x%10;
// if ans > INT_MAX/10 it will overflow
// if ans == INT_MAX/10 then if d > INT_MAX%10 will overflow.
// same logic for negative numbers
if(ans > poflow || (ans == poflow && d > poflowd)) return 0;
if(ans < noflow || (ans == noflow && d < noflowd)) return 0;
ans = ans * 10 + d;
x /= 10;
}
return ans;
}
};
Also read,
- Leetcode Reverse Integer problem solution in C
- Leetcode Reverse Integer problem solution in Java
- Leetcode Reverse Integer problem solution in Python
- Leetcode Reverse Integer problem solution in C#