首页 > 代码库 > Reverse Integer

Reverse Integer

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