Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123 Output: 321
Example 2:
Input: -123 Output: -321
Example 3:
Input: 120 Output: 21
//Time: O(n), Space:O(1) public int reverse(int x) { long result = 0;//为了防止溢出,用long来hold while (x != 0) { //无所谓正负 result = result * 10 + x % 10; if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) { return 0; } x = x / 10; } return (int) result; }