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) {
        long ans = 0;
        while(x!=0){
            ans = 10 * ans + (x%10);
            x /= 10;
        }
        return (ans<Integer.MIN_VALUE || ans>Integer.MAX_VALUE) ? 0 : (int)ans;
    }
}
comments powered by Disqus