首页 > 其他 > 详细

Reverse Integer

时间:2015-01-28 23:58:23      阅读:522      评论:0      收藏:0      [点我收藏+]

Reverse digits of an integer.

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

 

解法一:

public class Solution {
    public int reverse(int x) {
        
        if(x == 0){
            return 0;
        }
        
        String result = "";
        String flag = "";
        if(x<0){
            flag = "-";
        }
        ArrayList<String> list = new ArrayList<String>();
        while(x != 0){
            int temp = x%10;
            list.add(temp+"");
            x = x/10;
        }
       
        for(String e:list){
            result+=e;
        }
        
        result=flag+result.replace("-","");
        
        if(Double.valueOf(result)>Math.pow(2,31)-1||Double.valueOf(result)<-Math.pow(2,31)){
            return 0;
        }
        
        return Integer.valueOf(result);
        
    }
}

 

解法二:

public class Solution {
    public int reverse(int x) {
        String s = x+"";
        char[] char_array = s.toCharArray();
        int size = char_array.length;
        String re = "";
        for(int i=0;i<size;i++){
            re=re+char_array[size-i-1];
        }
        
        if(x<0){
            re="-"+re.replace("-","");
        }
        
        if(Double.valueOf(re)>Math.pow(2,31)-1||Double.valueOf(re)<-Math.pow(2,31)){
            return 0;
        }
        
        return Integer.valueOf(re);
        
    }
}

 

Reverse Integer

原文:http://www.cnblogs.com/mrpod2g/p/4257322.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!