Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
要求:不使用额外的内存空间。反转之后考虑越界问题。
public class Solution {
public int reverse(int x) {
long res = 0;//long类型是为了在反转的过程中,判断越界之前,已经超过了最值的情况。
int max = Integer.MAX_VALUE;
int min = Integer.MIN_VALUE;
while (x != 0) {
res = res * 10 + x % 10;
if(res > max || res < min){
return 0;
}
x = x / 10;
}
return (int)res;
}
}