码迷,mamicode.com
首页 > 其他好文 > 详细

Reverse Integer

时间:2015-01-29 00:00:26      阅读:313      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!