Name: Reverse Integer
Difficulty: Medium
Description: Reverse the given integer, maintain the negative sign
Example:
Input: x = 123 Output: 321 Input: x = -123 Output: -321 Input: x = 120 Output: 21
This was quite easy, except for overflows. You have to check the number never exceeds an integer. Other than that, it’s a matter of shifting result’s current value (result= result* 10), adding the last digit of x (+ x % 10), and removing the last digit from x (x /= 10). Loop until you’ve removed all the digits from x. Negatives are processed as positives, then converted back before returning.
int reverse(int x) {
bool isNegative{x < 0};
if (isNegative) {
if (x == INT_MIN) return 0;
x *= -1;
}
long long result{0};
while (x > 0) {
result = result * 10 + x % 10;
x /= 10;
}
if (result > INT_MAX) return 0;
if (isNegative) {
return (int)result * -1;
}
return (int)result;
}