7. Reverse Integer

Reverse digits of an integer.

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

思路1:讨巧的方法,用long,然后和MAX_VALUE和MIN_VALUE比

public class Solution {
    public int reverse(int x) {
        long tmp = 0;
        while (x!=0){
            tmp*=10;
            tmp+=x%10;
            if (tmp>Integer.MAX_VALUE||tmp<Integer.MIN_VALUE){
                return 0;
            }
            x/=10;
        }
        return (int)tmp;
    }
}

思路2:非常聪明的方法,如果溢出了则回不去了

public class Solution {
    public int reverse(int x) {
        int result = 0;
        while (x!=0){
            int tail = x%10;
            int newResult = result*10+tail;
            if ((newResult-tail)/10!=result){
                return 0;
            }
            result = newResult;
            x/=10;
        }
        return result;
    }
}

C++ code

class Solution {
public:
    int reverse(int x) {
        long res = 0;
        while (x!=0){
            res = res*10 + x%10;
            x = x/10;
            if (res>INT_MAX || res<INT_MIN){
                return 0;
            }
        }
        return (int)res;
    }
};

results matching ""

    No results matching ""