题解给的思路:
bool Flag_err=0; class Solution { public: int reverse(int x) { long y=0;//如果这里还是int,会在判断前就被裁剪了,无法判断溢出 bool flag=0; if(x<0) flag=1; while(x) { int ans=x%10; x=x/10; y=y*10+ans; if ((y > 0x7FFFFFFF && !flag) ||(y < (signed int)0x80000000 && flag))//检查溢出要判断向上还是向下溢出 { y=0; Flag_err=1; break; } } return y; } };
分析:我和题解的思路不同在于判断溢出的方式,我是设置了一个较大类型(long)的数字,然后根据符号位(flag)判断是否向上(y > 0x7FFFFFFF)还是向下(y < (signed int)0x80000000)溢出,注意这里必须要有signed int,不然默认无符号。
题解给的,因为int占4字节32位,根据二进制编码的规则,INT_MAX = 2^31-1,INT_MIN= -2^31. 然后判断十位及其以上超不超标,特殊情况下再判断个位超不超标。
感觉还是他的这个方法好点,起码占用空间比我那个小。
这个简单题我还写了小半天,完蛋玩意。