public int reverse(int x) {
if(x == 0)
return 0;
String s = Integer.toString(x);
//起点
boolean isNegative = false;
int start = 0;
if(s.charAt(0) == '-'){
//如果为负数
isNegative = true;
start ++;
}
//从后找到第一个非0的点
int back = s.length() - 1;
while(back >= 0 && s.charAt(back) == '0' ){
back--;
}
char[] c = new char[back - start + 1];
int i = 0;
int j=start;
for(;j<=back;j++){
c[i++] = s.charAt(j);
}
int tempStart = 0;
int tempEnd = i - 1;
while(tempStart < tempEnd){
char temp = c[tempStart];
c[tempStart] = c[tempEnd];
c[tempEnd] = temp;
tempStart++;
tempEnd--;
}
String ret = new String(c);
return isNegative ? -Integer.parseInt(ret) : Integer.parseInt(ret);
}
Reverse Integer
最新推荐文章于 2021-05-03 17:25:01 发布