Tuesday, February 23, 2016

[LeetCode] 7. Reverse Integer My

Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321

1. Special handling of overflow.

public class Solution {
    public int reverse(int x) {
        if (0 == x)
            return 0;
        boolean n = false;
        if (x < 0){
            x = x * -1;
            n = true;
        }
        int of = Integer.MAX_VALUE / 10;
        
        int res = 0;
        while(x > 0){
            if(res <= of){
                res *= 10;
                if(Integer.MAX_VALUE - res > x % 10){
                    res += x % 10;
                }
                x /= 10;
            }
            else{
                return 0;
            }
        }
        return n?res*-1:res;
        
    }
}

No comments:

Post a Comment