Simple Java Solution O(N) time and O(1) space.


  • 32
    A

    Simply just modulo the input by 10, add it to a long-integer variable as the result.
    Repeat. When the result is > max integer or < min integer, return 0. Hence, return the result as an integer

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

  • 0
    S

    It looks like convert to positive number is faster. Mine is 213 ms, yours are 244 ms.

      public int reverse(int x) {
        	if (x == Integer.MIN_VALUE)
        		return 0;
        	boolean minus = false;
        	if (x < 0){
        		x = Math.abs(x);
        		minus = true;
        	}
            long temp = 0;
            while(x != 0){
            	temp *= 10;
            	if (temp > Integer.MAX_VALUE || temp < Integer.MIN_VALUE)
            		return 0;
            	temp +=  x%10;
            	x /= 10;
            }
            if (minus)
            	return (int)(-temp);
            return (int)temp;
        }
    

  • 0
    T

    For another problem, I ran my accepted solution many times and the runtimes ranged from 199 - 229ms, so it's tough to say which solution above is really faster.


  • 0
    Z

    hello,i do not anderstand why compare the "result" with Integer.MAX_VALUE and Integer.MIN_VALUE, how about we compare "x" with them in the beginning
    i am a java newbie -_-


  • 0
    Z

    i see ,i see ...^-^


  • 0
    G

    If I am the interviewer, next question would be, what if input is long?
    are you going to use the no maxium value big integer class?


  • 0
    W

    why only if (x == Integer.MIN_VALUE) return 0? when x==integer.MAX_VALUE?


  • 0
    S

    Yes, you're right. But I submitted with my solution and the first solution sometimes, positive is always a little faster.


  • 0
    S

    It's the same result, but the following codes can solve MAXVALUE situation, abs function can't solve MINVALUE.


  • 0
    S

    @zishell 这个问题应该这样理解,输入的数x没有溢出,在反转之后可能会溢出,如Integer.MAXVALUE为2147483647,反转之后是7463847412产生了溢出,所以选择用表示范围比int更大的long类型存储转换之后的结果result。将反转之后的结果result与Integer.MAX_VALUE和Integer.MIN_VALUE作比较,如没有溢出,则将result强制转换为int返回,若有溢出,则返回0.


  • 0
    A

    @ardyadipta Shouldnt this give error as if any integer is > Integer.MAX_VALUE it would itself give a error on the place where result is calculated ? for example lets say when result==Integer.MAX_VALUE so if result+1 it would give integer overflow ?


  • 0
    A

    Ok got it ..taking long solved the overflow


Log in to reply
 

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