Java solution without long


  • 1
    T
    public class Solution {
    public int reverse(int x) {
        int sign = 1;
        if (x < 0){
            sign = -1;
            x = -x;
        }
        int ret = 0;
        while (x > 0){
            if (ret > 214748364)
                return 0;
            ret = ret*10 + x % 10;
            x /= 10;
        }
        return sign*ret;
    }
    }
    

    if ret == 214748364

    x /= 10 can only be 0 or 1

    There's no overflow


  • 0
    S

    I suggest to replacing 214748364 with Integer.MAX_VALUE/10


  • 2
    S

    Your code is the ideal code for this problem. However, I found out that for x = Integer.MIN_VALUE. -x = Integer.MIN_VALUE. And it happens that this case was skipped by while(x > 0). I think it's better to list it as an edge case. Updated code for reference.

    public class Solution {
        public int reverse(int x) {
            // edge case
            if(x==Integer.MIN_VALUE) return 0;
            // negative number, convert from positive
            if(x < 0) return -reverse(-x);
            
            int y = 0;
            while(x != 0){
                
                // edge case, overflow
                if(y > Integer.MAX_VALUE/10) return 0;
                
                y *= 10;
                y += x%10;
                x /= 10;
            }
            return y;
        }
    }

  • 0
    T

    Yes , I didn't realise the edge case Integer.MIN_VALUE may overflow,

    Thanks for your code review.


Log in to reply
 

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