the best performance solution in Java, beat 97.52%, by Chaoyang He


  • 1

    you only to check the overflow if reverse number is bigger than MAX_VALUE or smaller than MIN_VALUE.

    public class Solution {
        public int reverse(int x) {
            long result = 0;
            while (x != 0)
            {
                long tail = x % 10;
                long newResult = result * 10 + tail;
                if(newResult > Integer.MAX_VALUE || newResult < Integer.MIN_VALUE)
                { return 0; }
                result = newResult;
                x = x / 10;
            }
            return (int)result;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.