1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
|
public class ReverseInteger { public int reverse(int x) { int positive = x >= 0 ? 1 : -1; if (x == Integer.MIN_VALUE) { return 0; } x *= positive; if (x < 10) { return x; } int result = 0; do { if (result > Integer.MAX_VALUE / 10 || (result == Integer.MAX_VALUE / 10 && x % 10 > Integer.MAX_VALUE % 10)) { result = 0; break; } result = result * 10 + x % 10; x /= 10; } while (x > 0); if (result < 0) { return 0; } else { return positive * result; } } }
|