Reverse Integer
Reverse digits of an integer.
Example1:x = 123, return 321
Example2:x = -123, return -321
click to show spoilers.
Note:
The input is assumed to be a 32-bit signed integer. Your function shouldreturn 0 when the reversed integer overflows.
1.先记录符号
2.最后检查是否溢出int的范围
class Solution {
public int reverse(int x) {
boolean flag=(x>=0)?true:false;
long data=1;
int[] arr=new int[10];
int index=0;
x=Math.abs(x);
while(x>0){
arr[index]=x % 10;
x=x/10;
index++;
}
long result=0L;
for(int i=index-1;i>=0;i--){
result=result+arr[i]*data;
data=data*10;
}
if(result>Integer.MAX_VALUE || result<Integer.MIN_VALUE){
return 0;
}
return flag==true?(int)result:-(int)result;
}
}
网络答案
class Solution {
public int reverse(int x) {
long rev= 0;
while( x != 0){
rev= rev*10 + x % 10;
x= x/10;
if( rev > Integer.MAX_VALUE || rev < Integer.MIN_VALUE)
return 0;
}
return (int) rev;
}
}
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。