Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123 Output: 321Example 2:
Input: -123 Output: -321Example 3:
Input: 120 Output: 21Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
这个题,一个是如何表示2^32-1,一个是如何判断整数溢出
溢出真的是弄了很久,最后找到了一个比较合适的方法。ans类型是int64_t。后面每次都判断一下是否超出即可
class Solution { public: int reverse(int x) { //注意:不仅输入的数要在这个范围之内,输出的数也需要!!! if(x==0 || abs(x) > INT_MAX) //注意2^31-1的表示方法 return 0; int flag = x>0?1:-1;//记录符号 x = abs(x); int64_t ans=0; while(x){ ans = ans*10 + x; if(ans*flag >= INT_MAX || ans*flag <= INT_MIN) return 0; x /= 10; } return flag*ans; } };