题目:7 Reverse Integer
描述:
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123 Output: 321
Example 2:
Input: -123 Output: -321
Example 3:
Input: 120 Output: 21注意:
Assume we are dealing with an environment which could only hold integers within the32-bit signed integer range. For the purpose of this problem, assume that yourfunction returns 0 when the reversed integer overflows.
我的思路:
因为输入值x为整数,故主要可以利用字符串与整型数据相互转换的方法解决此问题。主要是利用valueOf()方法将整型数据x转化为String类型,然后用charAt()方法将其取出并将顺序颠倒,在将得到的字符数组转换成字符串,最后利用Integer.parseInt()方法将得到的字符串转换为整型数据并输出。String 类支持的方法,可以参看 Java String API 文档。
这道题主要需要注意对数据溢出的处理,即题目中要求输入值必须为32位的整型数据,输出数据也应为32位的整型数据,若不满足此要求则返回0。所以我们需要检测是否溢出。在做题时只注意到输出需为32位整型输入,而忽略了原本符合此条件的数据倒置之后的数字可能会发生溢出,所以最开始单纯用Integer.parseInt()方法将最后得到的字符串转换成整数,老是不能通过测试,提示NumberFormatException,仔细阅读了题目才解决了这个问题。
我的解决:
class Solution {
public int reverse(int x) {
if(x == 0)
return 0;
if(x > Integer.MAX_VALUE || x < Integer.MIN_VALUE)
return 0;
String str1 = String.valueOf(x);
String str2 = "";
if(str1.charAt(str1.length()-1) != '0'){
char data[] = new char[str1.length()];
if(str1.charAt(0) == '-'){
data[0] = '-';
for(int i = str1.length()-1 ; i >0 ; i --){
data[str1.length() - i] = str1.charAt(i);
}
str2 = new String(data);
try{
int Rx = Integer.parseInt(str2.trim());
return Rx;
}catch(NumberFormatException e){
return 0;
}
}
else{
for(int i = str1.length() - 1 ; i >= 0 ; i --){
data[str1.length() - 1 - i] = str1.charAt(i);
}
str2 = new String(data);
try{
int Rx = Integer.parseInt(str2.trim());
return Rx;
}catch(NumberFormatException e){
return 0;
}
}
}
else{
char data[] = new char[str1.length()-1];
if(str1.charAt(0) == '-'){
data[0] = '-';
for(int i = str1.length()-2 ; i > 0 ; i--){
data[str1.length()-1-i] = str1.charAt(i);
}
str2 = new String(data);
try{
int Rx = Integer.parseInt(str2.trim());
return Rx;
}catch(NumberFormatException e){
return 0;
}
}
else{
for(int i = str1.length()-2 ; i >= 0 ; i --){
data[str1.length() - 2 - i] = str1.charAt(i);
}
str2 = new String(data);
try{
int Rx = Integer.parseInt(str2.trim());
return Rx;
}catch(NumberFormatException e){
return 0;
}
}
}
}
}