14-Reverse Integer

思路:
先判定符号,整型范围[-2^32,2^32]
取余除10操作,依次进行,越界返回0
Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

#define IMAX numeric_limits<int>::max()
#define IMIN numeric_limits<int>::min()
class Solution {
public:
    int reverse(int x) {
        int sign= x>0?1:-1;
        if(x==IMIN)return 0;
        else x = abs(x);
        int res=0,count=0;
        for(;x;x/=10)
        {
            if(count>9)return (sign==1)?IMAX:IMIN;
            res = res*10;
            if(count==8){                         //倒数第二位向后看会不会越界,越界返回0
                if(sign==1&&res>IMAX/10)  return 0;
                if(sign==-1&&res*sign<IMIN/10)  return 0;
            }
            if(count==9){
                if(sign==1&&(IMAX-res<=x%10))return 0;//最后一位向后看不会越界,越界返回0
                if(sign==-1&&(res*sign-IMIN<=x%10)) return 0;
            }
            count++;
            res=x%10+res;
        }
        return res*sign;   
    }
};
原文地址:https://www.cnblogs.com/freeopen/p/5483009.html