2ms easy to understand java solution


  • 4
    M
    public class Solution {
    public int reverse(int x) {
        boolean isNegative = x < 0;
        x = Math.abs(x);
        int result = 0;
        int max_diff = Integer.MAX_VALUE / 10;
        while(x > 0) {
            if(result > max_diff) return 0;
            result = 10*result + x % 10;
            x /= 10;
        }
        return isNegative ? -result : result;
    }
    }

  • 1
    J

    You don't have to detect negative, % and / are negative compatible. And of course, you should check while (x!=0) instead.


  • 0
    M
    This post is deleted!

Log in to reply
 

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