leetcode [Reverse Integer]

public class Solution {  
    public int reverse(long a) {//题目中提到如果超过32-bit的返回0,想到的解决办法是用long来存,判断结果是否大于Integer.MAX_VALUE或小于Integer.MIN_VALUE  
        long temp = 0;  
        int res = 0;  
        if(a < 0){  
            a = Math.abs(a);  
            while(a != 0){  
                temp = temp * 10 + (a % 10);  
                a = a / 10;  
            }  
            if(-temp < java.lang.Integer.MIN_VALUE){  
                return 0;  
            }  
            else{  
                res = -(int)temp;  
            }  
        }  
        else{  
            while(a != 0){  
                temp = temp * 10 + (a % 10);  
                a = a / 10;  
            }  
            if(temp > java.lang.Integer.MAX_VALUE){  
                return 0;  
            }  
            else{  
                res = (int)temp;  
            }  
        }  
        return res;  
    }  
} 

 

posted @ 2017-12-03 13:53  melon1ce  阅读(53)  评论(0)    收藏  举报