Very easy to understand Java solution


  • 0
    T
    public class Solution {
        public int reverse(int x) {
            boolean flag = false;
            if(x<0) flag = true; //flag for tracking negative number
            if(x>=-9 && x<10) return x;
            x = Math.abs(x);
            
            long result = 0;
            while(x>0){
                result = (result*10)+(x%10);
                x/=10;
            }
            if(result>Integer.MAX_VALUE || result<Integer.MIN_VALUE) return 0; //if reversed number is out of int range, return 0.
            if(flag) result = -result; //if number was negative then add negative sign at the end
            return (int)result;
            
            
        }
    }
    

  • 0
    N

    Similar idea:

    public class Solution {
        
        private int _maxR = Integer.MAX_VALUE/10;
        
        public int reverse(int x) {
            int r = 0;
            while (x != 0)
            {
                if (Math.abs(r) > _maxR) return 0;
                r = r * 10 + x%10;
                x /=10;
            }
            return r;
        }
    }
    

  • 0
    T

    Yes, similar.

    public class Solution {
        public int reverse(int x) {
            int flag = 1;
            if(x<0) flag = -1;
            if(x>=-9 && x<10) return x;
            x = Math.abs(x);
            
            int result = 0;
            while(x>0){
                if(result > Integer.MAX_VALUE/10 || (result == Integer.MAX_VALUE/10 && x>7)){
                    return 0;
                }
                result = (result*10)+(x%10);
                x/=10;
            }
            return result*flag;
        }
    }
    

  • 0
    T

    In case if we have to return Integer.MAX_VALUE OR Integer.MIN_VALUE depending on the flag set instead of simply returning 0. In that case, this is useful.


Log in to reply
 

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