/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Reverse;
/**
*
* @author suisuihan
*/
public class Resverse {
public int reverse(int x) {
int ret = 0;
String temp = null;
if(x >= 0){
temp = String.valueOf(x);
}else{
temp = String.valueOf(Math.abs(x));
}
StringBuffer buf = new StringBuffer(temp);
temp = buf.reverse().toString();
if(x >=0){
try {
ret = Integer.valueOf(temp);
} catch (Exception e) {
if(e.toString().contains("NumberFormatException")){
ret = 0;
}
}finally{
return ret;
}
}else{
try {
ret = 0 - Integer.valueOf(temp);
} catch (Exception e) {
if(e.toString().contains("NumberFormatException")){
ret = 0;
}
}finally{
return ret;
}
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
int x = 987654321;
Resverse test = new Resverse();
System.out.println(test.reverse(x));
}
}
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!
If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.
Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?
For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
Update (2014-11-10):
Test cases had been added to test the overflow behavior.
1、思路:不知道算不算取巧,思路是直接将int转换为string,利用stringbuffer的reverse功能。
2、使用时在想如果越界了怎么办,结果抛出java.lang.NumberFormatException: For input string: "987654321"异常。catch之后搞定。