Reverse Integer

Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

Input: 123 Output: 321

Example 2: Input: -123 Output: -321

Example 3: Input: 120 Output: 21

Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

Solution: Divide by 10 to check overflow

    int reverse(int x) {
        int ans = 0;
        while (x) {
            int temp = ans * 10 + x % 10;
            if (temp / 10 != ans) return 0;
            ans = temp;
            x /= 10;
        }
        return ans;
    }

Solution: Using vector

int reverse(int x) {
    int sign = x > 0 ? 1 : -1;
    vector<int> v;
    while (x != 0) {
        int digit = x % 10;
        x /= 10;
        v.push_back(digit);
    }

    int r = 0;
    for (auto d: v) {
        if ( r > 0 && INT_MAX / 10 < r) return 0;
        if ( r < 0 && INT_MIN / 10 > r) return 0;
        r *= 10;

        if ( r > 0 && INT_MAX - d < r) return 0;            
        if ( r < 0 && INT_MIN - d > r) return 0;
        r += d;
    }

    return r;
}

Solution: Using long long

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

results matching ""

    No results matching ""