Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Reverse {
- private static final int max = Integer.MAX_VALUE;
- private static final int min = Integer.MIN_VALUE;
- public int reverse(int x) {
- // setup -> reduce the problem to 'positive int' (maybe unnecessary)
- boolean isNegative = (x < 0);
- int upperBound = Math.abs(isNegative ? min / 10 : max / 10);
- int check = Math.abs(isNegative ? min % 10 : max / 10);
- x = Math.abs(x);
- int ret = 0;
- while (x != 0) {
- int digit = x % 10;
- x /= 10;
- if ((ret > upperBound) || (ret == upperBound) && (digit == check)) {
- return 0;
- }
- ret = 10 * ret + digit;
- }
- return isNegative ? -1 * ret : ret;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement