Advertisement
gelita

Reverse a signed 32 bit int

Mar 14th, 2020
799
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 0.98 KB | None | 0 0
  1. /*
  2. Given a 32-bit signed integer, reverse digits of an integer.
  3.  
  4. Example 1:
  5.  
  6. Input: 123
  7. Output: 321
  8. Example 2:
  9.  
  10. Input: -123
  11. Output: -321
  12. Example 3:
  13.  
  14. Input: 120
  15. Output: 21
  16. Note:
  17. Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231,  231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows./*
  18.  
  19. */
  20. class Solution {
  21.     public int reverse(int x) {
  22.         int result = 0;
  23.         while(x != 0){
  24.             int lastDigit = x % 10;
  25.             x /= 10;
  26.             //check for overflow
  27.             if(result>Integer.MAX_VALUE/10 || (result == Integer.MAX_VALUE/10 && lastDigit>7)){
  28.              return 0;
  29.             }
  30.             if(result<Integer.MIN_VALUE/10 || (result == Integer.MIN_VALUE/10 && lastDigit <-8)){
  31.                 return 0;
  32.             }
  33.             result = result*10 + lastDigit;
  34.         }
  35.         return result;
  36.     }
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement