LeetCode第7题String Integer

来源:互联网 发布:office 2016 for mac 编辑:程序博客网 时间:2024/06/05 15:50
public class Solution {
    public static int reverse(int x) {
// TODO Auto-generated method stub
String str = String.valueOf(x);
//将int型转化为String型
int length = str.length();
//计算字符串的长度
char[] strChar = str.toCharArray();
//将字符串转换为字符数组
//String str = Integer.toString(x);
int result = 0;

if(x < 0){
int i = 1;
int j = length - 1;
char temp;
while(i < j){
temp = strChar[i];
strChar[i] = strChar[j];
strChar[j] = temp;
i++;
j--;
}
}

else{
int i = 0;
int j = length - 1;
char temp;
while(i < j){
temp = strChar[i];
strChar[i] = strChar[j];
strChar[j] = temp;
i++;
j--;
}
}
String strResult = new String(strChar);
//拼接字符数组为字符串
double longResult = Double.parseDouble(strResult);
//将字符串转换为对应的Double型数字
if(longResult < 2147483647 && longResult > -2147483648 )
   result =(int)longResult;

return result;
}


}
0 0