Reverse Number

Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-2^31, 2^31 - 1], then return 0.

Assume the environment does not allow you to store 64-bit integers (signed or unsigned).

Example 1:

Input: x = 123
Output: 321
Example 2:

Input: x = -123
Output: -321
Example 3:

Input: x = 120
Output: 21

Constraints:

-231 <= x <= 231 - 1

Solution

public int Reverse(int x) {
    long result = 0;
    while (x != 0) {
        result = result * 10 + x % 10;
        x /= 10;
        if (result > Int32.MaxValue || result < Int32.MinValue) {
            return 0;
        }
    }
    return (int)result;
}

The time complexity of the algorithm is O(log(x)), where x is the input to the function. This is because in each iteration of the while loop, we’re dividing x by 10, effectively reducing the problem size by a factor of 10. Hence, the number of iterations is proportional to the number of digits in x, which is log(x) in base 10.

The space complexity of the algorithm is O(1), which means it uses a constant amount of space. This is because we’re only using a fixed number of variables and not any data structures that grow with the size of the input. The integer result and the input x are the only variables being used, and their size does not change with different inputs.

Last updated