7. 整数反转 考虑溢出

  1. class Solution {
  2. public int reverse(int x) {
  3. int ans = 0;
  4. while (x != 0) {
  5. int pop = x % 10;
  6. if (ans > Integer.MAX_VALUE / 10 || (ans == Integer.MAX_VALUE / 10 && pop > 7))
  7. return 0;
  8. if (ans < Integer.MIN_VALUE / 10 || (ans == Integer.MIN_VALUE / 10 && pop < -8))
  9. return 0;
  10. ans = ans * 10 + pop;
  11. x /= 10;
  12. }
  13. return ans;
  14. }
  15. }
x pop ans
1234 0
123 4 4
12 3 43
1 2 432
0 1 4321