• 先全部转为负数处理(因为负数比正数多一个有效位)
    • 其他没什么好说的,主要是检测越界问题
    1. public static int reverse(int x) {
    2. boolean o = ((x >>> 31) & 1) == 1;
    3. int count = 0;
    4. int m = Integer.MIN_VALUE / 10;
    5. int n = Integer.MIN_VALUE % 10;
    6. x = o ? x : -x;
    7. while (x != 0) {
    8. if (count < m || (count == m && x % 10 < n) ) {
    9. return 0;
    10. }
    11. count = count * 10 + x % 10;
    12. x /= 10;
    13. }
    14. return o ? count : -count;
    15. }