Short java solution


  • 3
    J
        public int reverse(int x) {
            int res = 0;
            boolean flag = x > 0;
            while(x!=0){
                if(Math.abs(res)>214748364||Math.abs(res)==214748364&&Math.abs(x%10)>((flag)?7:8))   return 0;
                res = res*10+x%10;
                x/=10;
            }
            return res;
        }

  • 0
    J

    what is wrong with my code???

    public class Solution {
    public int reverse(int x) {
    int temp=x;
    int sum=0;

        while(temp!=0){
            sum=sum*10+temp%10;
            temp/=10;
        }
        
        return sum;
    }
    

    }


  • 0
    G

    Doesn`t check for overflow.


  • 0
    G

    What is this check for Math.abs(x%10)>((flag)?7:8))

    I understood it. Pretty good soln.


  • 0
    W

    why use Math.abs(x%10)>((flag)?7:8))?


  • 0
    J

    @gjhawar Actually I was over thinking. Since input x is an int, the situation Math.abs(res)==214748364&&Math.abs(x%10)>((flag)?7:8) will not possibly happen. So the flag is also removeable


Log in to reply
 

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