Reverse Integer

题目

Given a 32-bit signed integer, reverse digits of an integer.

答案
key: 用long 判断是否overflow

class Solution {
    public int reverse(int x) {
        boolean sign = x > 0;
        x = Math.abs(x);
        long ans = 0;
        // Reverse digits now
        while(x > 0) {
            int t = x % 10;
            x = x / 10;
            long candidate = ans * 10 + t;
            // Overflow, just return 0
            if(candidate > Integer.MAX_VALUE) return 0;
            ans = (int)candidate;
        }
        
        return (int)ans * (sign?1:-1);
    }
}

你可能感兴趣的:(Reverse Integer)