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
最新推荐文章于 2020-07-05 10:18:11 发布
本文介绍了一种使用Java实现的整数反转算法。该算法首先判断输入整数是否为负数,并从输入整数的字符串表示中去除前导零。然后通过字符数组进行反转操作,最后将反转后的字符数组转换回整数类型。
364

被折叠的 条评论
为什么被折叠?



