7 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 hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

分析

Difficulty: Easy

这道题主要需要注意一下翻转后int类型溢出的问题

代码

class Solution {
public:
    int reverse(int x) {
        //需要注意下溢出
        long long res = 0;
        //正负不影响
        while(x != 0)
        {
            res = res * 10 + x % 10;
            x /= 10;
        }
        cout << res;
        if (res<INT_MIN||res>INT_MAX) 
            return 0;
        else 
            return res;
    }
};
 
comments powered by Disqus