马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
7. Reverse Integer #Easy
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).
Example 1:
Input: x = 123
Output: 321
Example 2:
Input: x = -123
Output: -321
Example 3:
Input: x = 120
Output: 21
Example 4:
Input: x = 0
Output: 0
Constraints:
-231 <= x <= 231 - 1
C#include <limits.h>
#include <stdbool.h>
int reverse(int x){
int n = 0;
int r = 0;
bool is_negative = false;
if (x < 0) {
is_negative = true;
}
if (x == INT_MIN) {
return 0;
}
int y = abs(x);
while (y >= 0) {
r = y % 10;
if ((y / 10)== 0) {
if (n > (INT_MAX / 10)) {
return 0;
} else if ((n == (INT_MAX / 10)) && is_negative && (r > ((INT_MAX % 10) + 1))) {
return 0;
} else if ((n == (INT_MAX / 10)) && !is_negative && (r > (INT_MAX % 10))) {
return 0;
} else {
n = (n * 10) + r;
if (is_negative) {
return (n * -1);
} else {
return n;
}
}
} else {
n = (n * 10) + r;
y = y / 10;
}
}
return -1;
}
!!!good style -> always return sth.
!!!special case -> INT_MIN
!!!negative sign -> bool is_negative
!!!integer overflow -> check before reversing ur last digit |