LeetCode7 Reverse Integer

题意: 

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321 (Easy)

分析:

思路很简单,注意特殊情况如10,100等和int溢出情况即可;

开始采用的是用一个数组把各位先存起来,再以此乘以相应的系数组成结果,但是这样写代码冗长而且费空间;

直接采用一个while循环即可;

代码1:

 1 class Solution {
 2 public:
 3     int reverse(int x) {
 4         long long result = 0;
 5         while (x != 0) {
 6             int temp = x % 10;
 7             x /= 10;
 8             result = result * 10 +  temp;
 9             if (result > 0x7FFFFFFF || result < -0x7FFFFFFF) {
10                 return 0;
11             }
12         }
13         return result;
14     }
15 };

查看讨论区,发现有一种不用0x7FFFFFFF判断的实现方式,作为参考;

代码2:

 1 class Solution {
 2 public:
 3     int reverse(int x) {
 4         int result = 0;
 5         while (x != 0) {
 6             int temp = x % 10;
 7             x /= 10;
 8             int newResult = result * 10 +  temp;
 9             if ( (newResult - temp) / 10 != result) {
10                 return 0;
11             }
12             result = newResult;
13         }
14         return result;
15     }
16 };
原文地址:https://www.cnblogs.com/wangxiaobao/p/5734707.html