您的位置:首页 > 编程语言 > C语言/C++

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

2017-10-11 11:51 435 查看

题目:

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode Reverse Integer C