美文网首页
7. Reverse Integer

7. Reverse Integer

作者: 今有所思 | 来源:发表于2017-03-03 08:01 被阅读17次
    Reverse digits of an integer.
    
    Example1: x = 123, return 321
    Example2: x = -123, return -321
    
    
    Note:
    The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.
    
    public class ReverseInteger {
        public static int reverse(int x) {
            if(x == -2147483648)
                return 0;
            int[] max = {2, 1, 4, 7, 4, 8, 3, 6, 4, 7};
            int res = 0;
            int cnt = 0;
            boolean overflow = true;
            boolean flag = false;
            boolean change = false;//没有确定是否溢出
            if(x < 0) {
                x = -x;
                max[9] += 1;//负数最大为-2147483648
                flag = true;
            }
            
            while(x != 0) {
                int t = x % 10;
                if(!change && t > max[cnt]) {
                    overflow = true;
                    change = true;
                }
                if(!change && t < max[cnt]) {
                    overflow = false;
                    change = true;
                }
                cnt++;
                if(cnt == 10 && overflow) {
                    return 0;
                }
                res = res * 10 + t;
                x /= 10;
            }
            if(flag)
                res = -res;
            return res;
            
        }
        public static void main(String[] args) {
            System.out.println(reverse(-2147483648));   
        }
    
    }
    
    
    public int reverse(int x){
        int result = 0;
    
        while (x != 0){
            int tail = x % 10;
            int newResult = result * 10 + tail;
            if ((newResult - tail) / 10 != result) { 
                return 0; 
            }
            result = newResult;
            x = x / 10;
        }
    
        return result;
    }
    

    相关文章

      网友评论

          本文标题:7. Reverse Integer

          本文链接:https://www.haomeiwen.com/subject/ovrlgttx.html