DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Kaitian Xie
Kaitian Xie

Posted on • Updated on

LeetCode 7. Reverse Integer

public int reverse(int x) {
    int rev = 0;

    while (x != 0) {
        int pop = x % 10;
        x /= 10;

        if (rev > Integer.MAX_VALUE / 10 || (rev == Integer.MAX_VALUE / 10 && pop > 7)) {
            return 0;
        }
        if (rev < Integer.MIN_VALUE / 10 || (rev == Integer.MIN_VALUE / 10 && pop < -8)) {
            return 0;
        }

        rev = rev * 10 + pop;
    }

    return rev;
}

Reversing an integer is similar to reversing String. We get the last digit x % 10 and add it to rev. We repeat this process until x is 0. The two if statements are used to prevent integer overflows.

Time Complexity: O(log(x))

Extra Space: O(1)

A note on integer overflows

A integer occurs when the sum of rev * 10 + pop is greater/less than the maximum value (Integer.MAX_VALUE)/the minimum value(Integer.MIN_VALUE). So we need the check the values of rev and pop.

  • If rev > Integer.MAX_VALUE/10 or rev < Integer.MIN_VALUE/10, rev * 10 + pop will overflow.
  • If rev == Integer.MAX_VALUE / 10, pop must be less than or equal to 7 because 2^32 - 1 % 10 == 7.
  • If rev == Integer.MIN_VALUE / 10, pop must be greater than or equal to -8 because -2^32 % 10 == 8.

Top comments (0)

An Animated Guide to Node.js Event Lop

Node.js doesn’t stop from running other operations because of Libuv, a C++ library responsible for the event loop and asynchronously handling tasks such as network requests, DNS resolution, file system operations, data encryption, etc.

What happens under the hood when Node.js works on tasks such as database queries? We will explore it by following this piece of code step by step.