Leetcode5: Reverse Integer

来源:互联网 发布:hmcl启动器json 编辑:程序博客网 时间:2024/06/13 02:56

Reverse digits of an integer.

Example1: x = 123, return 321

Example2: x = -123, return -321


给出大牛的解法,这题实在不知道怎么解,原谅LZ的智障 -。-

class Solution {public:    int reverse(int x) {        int sign = x > 0 ? 1:-1;        long temp = 0;        while(x)        {            temp = temp*10 + x%10;            x /= 10;        }        if(temp > 2147483647 || sign*temp > 2147483647)                return 0;        else        {        return temp;        }    }};
其中2147483647是2的31次方-1,是32位操作系统中最大的符号型整型常量。
所以这里一定要有判断,否则会溢出。



0 0
原创粉丝点击