题目链接:Reverse Integer

Reverse digits of an integer.

Example1: x = 123, return 321

Example2: x = -123, return -321

Have you thought about this?

Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!

If the integer’s last digit is 0, what should the output be? ie, cases such as 10, 100.

Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?

For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

这道题的要求是翻转整数,例如:输入123,输出321;输入-123,输出-321。

思路是不断用输入数据模10取每位上的数字。可能需要考虑以下几个问题:

  • 负数问题:如果输入数字是负数,由于-123 % 10 = -3,因此无需特殊考虑负数。
  • 溢出问题:为了检测溢出而不提升数据类型(不采用long long),可以在结果乘以10之前判断是否大于INT_MAX/10(即214748364)或者小于INT_MIN/10(即-214748364)。如果等于INT_MAX/10时,由于输入数据在int范围内,因此可以确定,最后1个数字一定是1或者2,所以一定不会溢出。

时间复杂度:O(n)(取决于整数位数)

空间复杂度:O(1)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution 
{
public:
    int reverse(int x) 
    {
        int res = 0;
        while(x != 0)
        {
            if(abs(res) > 214748364)
                return 0;
            res = res * 10 + x % 10;
            x /= 10;
        }
        
        return res;
    }
};