-1

Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.

In this code I want to know about (rev == Integer.MAX_VALUE / 10 && pop > 7) and (rev == Integer.MIN_VALUE / 10 && pop < -8)

Why do they use pop>7 and pop<-8?

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

        while (x != 0) {
            int pop = x % 10;
            x /= 10;
            if (rev > Integer.MAX_VALUE/10 || (rev == Integer.MAX_VALUE / 10 && pop > 7)) return 0;
            if (rev < Integer.MIN_VALUE/10 || (rev == Integer.MIN_VALUE / 10 && pop < -8)) return 0;
            rev = rev * 10 + pop;
        }

        return rev;
    }
}
beaker
  • 16,331
  • 3
  • 32
  • 49
Saif Ali
  • 19
  • 4
  • The max integer value is 2147483647. It's doing the boundary check in those two IF statements. Because the returned value (rev) is multiplied by 10 and adds pop, it checks if the rev value equals 214748364 (max int value divided by 10) and that pop is not higher than 7. Because if those values are, then in the final calculation it will be outside the integer's max range. – Phaelax z Jun 24 '21 at 14:01
  • The solution in Javascript https://stackoverflow.com/questions/28572952/reverse-digits-of-an-integer/74655340#74655340 – Ashish Dec 02 '22 at 11:58

2 Answers2

0
class Solution {
    public  int reverse(int x) {
   
        int ans=0;
        while(x!=0)
        {
            int digit=x%10;
            if( (ans>Integer.MAX_VALUE/10)   || (ans<Integer.MIN_VALUE/10)   )   
            {
                return 0;
            }
            ans=(ans*10)+digit;
            x=x/10;
            
        }
        return ans;
    }
        
        public  void main(String[] args)
        {
            int x=120;
           System.out.print("Reversed Number is "+ reverse(x));
        }
        
}
S.B
  • 13,077
  • 10
  • 22
  • 49
  • Thank you for this code snippet, which might provide some limited, immediate help. A [proper explanation](https://meta.stackexchange.com/q/114762/349538) would greatly improve its long-term value by showing why this is a good solution to the problem and would make it more useful to future readers with other, similar questions. Please [edit] your answer to add some explanation, including the assumptions you’ve made. – helvete Jan 25 '22 at 15:02
  • Javascript-based solution. Hope it helps https://stackoverflow.com/questions/28572952/reverse-digits-of-an-integer/74655340#74655340 – Ashish Dec 02 '22 at 11:59
-1

-2147483648 to 2147483647 signed integer range if condition true when the rev integer is equal to maximum integer value ,rev==(2147483647) and the last digit of given integer is greater then 7 than only enters in the if condition return 0. same as above next if also do check the same condition with (-2147483648).

pnagde
  • 1
  • 1