Solution in Java


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

  • 0
    2

    Instead of if(result > Integer.MAX_VALUE/10 || result < Integer.MIN_VALUE/10),
    what you can do is put if (Math.abs(result) > Integer.MAX_VALUE/10) there. This is more concise.


Log in to reply
 

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