问题描述:
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
解答思路
使用字符数组
public class Solution {
public int reverse(int x){
boolean flag=true;
if(x<0){
flag=false;
}char[] str={};
try{
str=String.valueOf(x).toCharArray();
}catch(Exception e){
e.printStackTrace();
}
int length=str.length;
char c;
for(int i=0,j=length-1;i<=j;){
c=str[i];
str[i++]=str[j];
str[j--]=c;
}
int r = 0;
try{
if(flag){
r = Integer.valueOf(new String(str));
}
else{
r = -Integer.valueOf(new String(str, 0, length-1));
}
}catch(Exception e){
e.printStackTrace();
}
return r;
}
}
改进的算法
public class Solution {
public int reverse(int x) {
int num = 0;
while (x!=0) {
int temp = num * 10 + x % 10;
x /= 10;
if (temp/10!=num) {
num=0;
break;
}
num=temp;
}
return num;
}
}