Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

click to show spoilers.

Have you thought about this?

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.

刚开始没看到spoilers,不知道越界如何处理。坑....将int反转变为String反转做的。
public class Solution {
    public int reverse(int x) {
        
        if(x<0){
            int n=-x;
            String s=String.valueOf(n);
            String temp=re(s);
            try{
                int m=-Integer.parseInt(temp);
                return m;
            }catch(java.lang.NumberFormatException e){
                return 0;
            }
        }else {
            String s=String.valueOf(x);
            String temp=re(s);
            try{
                int m=Integer.parseInt(temp);
                return m;
            }catch(java.lang.NumberFormatException e){
                return 0;
            }
            
            
        }
    }
    
    public String re(String s){
        String t=new String();
        int m=s.length();
        for(int i=m-1;i>=0;i--){
            t=t+s.charAt(i);
        }
        return t;
    }
}
View Code

 

posted on 2015-06-11 23:56  gone~with~wind  阅读(87)  评论(0编辑  收藏  举报