LeetCode 7. Reverse Integer ( 简单题,注意INT_MAX 和INT_MIN就可以 )

这道题也是信心题~~

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.

AC代码:

class Solution {
public:
    int reverse(int x) {
       long int reverseNum = 0;
       
        while(x != 0){ //负数也可以的,不用单独考虑;第一个数为0也不用单独考虑
            reverseNum = (reverseNum * 10.0) + x % 10;
            x /= 10;
        }
        
        if(reverseNum < INT_MAX && reverseNum > INT_MIN)
            return reverseNum;
        return 0;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_25175067/article/details/80390471
今日推荐