Java-simple-fast-o(n)-no-convert


  • 4
    R
    public class Solution {
        public int reverse(int x) {
    
            int result = 0;
    
            int flag = x<0?-1:1;
            x=x*flag;
            
    
            while (x>0){
            // after the multiply is should not exceed
                if(Integer.MAX_VALUE/10<result){
                    return 0;
                }
            // after the multiply and the increase, it should not exceed
                if(Integer.MAX_VALUE -result*10 < (x%10)){
                    return 0;
                }
                result = (x%10)+result*10;
                x/=10;
            }
    
            return result*flag;
        }
    }

  • 0
    I

    what is the purpose of your 2nd if statement in the while loop?


  • 0
    W

    Similar thought, but avoid the overflow caused by Integer.MIN_VALUE.

    public class Solution {
        public int reverse(int x) {
            boolean negative = false;
            int res = 0;
            if(x < 0)  {
                if(x == Integer.MIN_VALUE) return 0;
                x = -x;
                negative = true;
            }
            while(x / 10 != 0) {
                res = 10 * res + x % 10;
                if(res > Integer.MAX_VALUE / 10) return 0;
                x /= 10;
            }
            res = 10 * res + x;
            return negative ? -res : res;
        }
    }

  • 0
    R

    add some comments as your questioning


  • 0
    P

    Isn't the below check good enough for checking overflow

     if(x%10!=res%10) return 0; 

Log in to reply
 

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