【JAVA、C++】LeetCode 007 Reverse Integer

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

解题思路:
将数字翻转并不难,可以转成String类型翻转,也可以逐位翻转,本题涉及到的主要是边界和溢出问题,使用Long或者BigInteger即可解决。

题目不难:

JAVA实现如下:

public class Solution {
    static public int reverse(int x) {
        if(x==0||x==-2147483648)return 0;
        boolean isNagetive=false;
        if(x<0){
            isNagetive=true;
            x=-x;
        }
        long result=0;
        while(x!=0){
            result*=10;
            result+=x%10;
            x/=10;
        }
        final int INT_MAX=0x7fffffff;
        if((result-INT_MAX)>0)
            return 0;

        if(isNagetive)result=-result;
        return (int)result;
    }
}

 C++实现如下:

 1 #include<algorithm>
 2 using namespace std;
 3 class Solution {
 4 public:
 5     int reverse(int x) {
 6         if (x == INT_MIN)
 7             return 0;
 8         bool isNeg = x < 0;
 9         x = abs(x);
10         long res = 0;
11         while (x) {
12             res = res * 10 + x % 10;
13             if (res > INT_MAX)
14                 return 0;
15             x /= 10;
16         }
17         return isNeg ? -(int)res: (int)res;
18     }
19 };
原文地址:https://www.cnblogs.com/tonyluis/p/4456713.html