Reverse Integer

Reverse digits of an integer.

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

class Solution {
public:
    int reverse(int x) {
        int sign = 1;
        if(x < 0) sign = -1;
        if(x == INT_MIN)    return 0;
        x = abs(x);

        long long reverse = 0;

        while(x){
            reverse = reverse * 10 + x%10;
            x /= 10;
            if(reverse > INT_MAX) return 0;
        }

        return (int)sign*reverse;
    }
};
class Solution {
public:
    int reverse(int x) {
        long long reverse = 0;

        while(x){
            reverse = reverse * 10 + x%10;
            x /= 10;
            if(reverse > INT_MAX || reverse < INT_MIN) return 0;
        }

        return (int)reverse;
    }
};

results matching ""

    No results matching ""