[leetcode]Reverse Integer 代码(C++)

来源:互联网 发布:淘宝怎么寄到美国 编辑:程序博客网 时间:2024/05/16 13:43

题目:

Reverse digits of an integer.

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

click to show spoilers.

Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.

解题:

这道题很简单,但是我们也不能大意。写代码的时候要注意区分正负号,题目给出的是32-bit,注意溢出问题

代码如下:

class Solution {
public:
    int reverse(int x) {    //注意:1.区分正负数  2.因为条件是32-bit,判断溢出 INT_MIN and INT_MAX
        int i;
        long sum=0;
        int sign=1;
        if(x<0) {x=-x;sign=-1;}
        while(x){
            sum=sum*10+x%10;
           
            x/=10;
        }
        return (sum<INT_MIN||sum>INT_MAX)?0:sum*sign;
    }
};


end