【Leetcode】【Easy】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.

注意:

此题在2014年11月10日前,对结果没有加入整数溢出的测试。加上后,下面代码存在Bug(1027 / 1032 test cases passed)。

 1 class Solution {
 2 public:
 3     int reverse(int x) {
 4        int res = 0;
 5        
 6        while (x) {
 7            res = 10 * res + x % 10;
 8            x /= 10;
 9        }
10        
11        return res;
12     }
13 }; 

原因:int占用4个字节,能表示的范围是:-2,147,483,648 ~ 2,147,483,647。当反转时会遇到“10 * res”的过程,也就是此整数正着可能不越界,但是倒过来就会越界。

解题思路1:

在“10 * res”前加上判定语句,防止越界。

注意:

1、对2^31/10进行判定,不要对2^31进行判定,也就是不要和准确的边界值比大小。因为当整数已经越界时,它的值自动变化,再拿它比较永远不会越界;

2、注意多个&& || 混合时的优先级问题;

AC代码:

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

解题思路2:

直接声明res为long(未适应32位和64位,应该是long long),这样就不会在计算中对long越界,返回结果时再判断是否对int越界;

 1 class Solution {
 2 public:
 3     int reverse(int x) {
 4         long res = 0;
 5        
 6         while (x) {
 7             res = 10 * res + x % 10;
 8             x /= 10;
 9         }
10         
11         if ((res>INT_MAX) || (res < INT_MIN))
12             res = 0;
13         
14         return res;
15     }
16 };
原文地址:https://www.cnblogs.com/huxiao-tee/p/4186051.html