Given a 32-bit signed integer, reverse digits of an integer.

Note:
Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range.

重点来了:

For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
所以我们应该考虑溢出,我们用一个long的数据类型来容纳int类型的运输,以保证运算不会在long数据类型上发生溢出。

上代码:

class Solution {
public:
    int reverse(int x) {
        int flag = 1;
        if(x < 0){
            flag = -1; 
            x  = -x;
        } 
        long long sum = 0;          //用long来得到结果
        while(x){
            sum = (sum * 10 + (x % 10));
            x /= 10;
        }
        sum = sum * flag;
        return (sum  > INT_MAX || sum < INT_MIN)? 0 : sum;
    }
};

你可能感兴趣的:(Given a 32-bit signed integer, reverse digits of an integer.)