首页 > 代码库 > LeetCode --- 7. Reverse Integer

LeetCode --- 7. Reverse Integer

题目链接: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 class Solution 
 2 {
 3 public:
 4     int reverse(int x) 
 5     {
 6         int res = 0;
 7         while(x != 0)
 8         {
 9             if(abs(res) > 214748364)
10                 return 0;
11             res = res * 10 + x % 10;
12             x /= 10;
13         }
14         
15         return res;
16     }
17 };

转载请说明出处:LeetCode --- 7. Reverse Integer

LeetCode --- 7. Reverse Integer