Reverse digits of an integer.
- Example1: x = 123, return 321
- Example2: x = -123, return -321
C Solution:
int reverse(int x) {
if (x == INT_MIN) return 0;
int sign = 1;
if (x < 0) {
sign = -1;
x = -x;
}
int limit = INT_MAX / 10, _limit = INT_MAX % 10;
int res = 0;
while (x && res < limit) {
res = res * 10 + x % 10;
x /= 10;
}
if (!x) return res * sign;
if (res > limit) return 0;
if (x > _limit) return 0;
return (res * 10 + x) * sign;
}
Summary:
- Math is tricky during being represented on computer.
LeetCode: 7. Reverse Integer
近期评论