其他分享
首页 > 其他分享> > Leetcode7:Reverse Integer

Leetcode7:Reverse Integer

作者:互联网

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

Example 1:

Input: 123
Output: 321
Example 2:

Input: -123
Output: -321
Example 3:

Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
反转数字要注意的问题就是溢出的问题,int型的数值范围是 -2147483648~2147483647,要是来个1999999999让你反是反不过来的,题目让你传回int,很明显溢出了,怎么办,方法一,用long去接:

C++
int reverse(int x) {
        long res = 0;
        while (x != 0) {
            res = 10 * res + x % 10;
            x /= 10;
        }
        return (res > INT_MAX || res < INT_MIN) ? 0 : res;
    }

当然也可以不这样,人家让你反,反不过来返回0就好,可以在反转过程中判断溢出,不需要long。

C++
nt reverse(int x) {
        int res = 0;
        while(x)
        {
            if(res > INT_MAX / 10||res < INT_MIN / 10)return 0;
            res = res * 10 + x % 10;
            x = x/10;
        }
        return res;
    }

标签:Leetcode7,Reverse,10,int,res,INT,integer,Integer,Input
来源: https://blog.csdn.net/qq_34314736/article/details/96473574