Advertisement
Guest User

Untitled

a guest
Jan 16th, 2019
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.68 KB | None | 0 0
  1. public class Reverse {
  2. private static final int max = Integer.MAX_VALUE;
  3. private static final int min = Integer.MIN_VALUE;
  4.  
  5. public int reverse(int x) {
  6. // setup -> reduce the problem to 'positive int' (maybe unnecessary)
  7. boolean isNegative = (x < 0);
  8. int upperBound = Math.abs(isNegative ? min / 10 : max / 10);
  9. int check = Math.abs(isNegative ? min % 10 : max / 10);
  10.  
  11. x = Math.abs(x);
  12. int ret = 0;
  13.  
  14. while (x != 0) {
  15. int digit = x % 10;
  16. x /= 10;
  17. if ((ret > upperBound) || (ret == upperBound) && (digit == check)) {
  18. return 0;
  19. }
  20. ret = 10 * ret + digit;
  21. }
  22. return isNegative ? -1 * ret : ret;
  23. }
  24. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement