<p>Given a signed 32-bit integer <code>x</code>, return <code>x</code><em> with its digits reversed</em>. If reversing <code>x</code> causes the value to go outside the signed 32-bit integer range <code>[-2<sup>31</sup>, 2<sup>31</sup> - 1]</code>, then return <code>0</code>.</p>

<p><strong>Assume the environment does not allow you to store 64-bit integers (signed or unsigned).</strong></p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> x = 123
<strong>Output:</strong> 321
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> x = -123
<strong>Output:</strong> -321
</pre>

<p><strong class="example">Example 3:</strong></p>

<pre>
<strong>Input:</strong> x = 120
<strong>Output:</strong> 21
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>-2<sup>31</sup> &lt;= x &lt;= 2<sup>31</sup> - 1</code></li>
</ul>

class Solution {
public:
    int reverse(int x) {
        // Return immediately if x is zero
        if(x == 0) return x;

        int rev = 0;  // This will store the reversed number
        int temp;     // Temporary variable to hold the last digit
        bool negative = false;  // Flag to check if the number is negative

        // If x is negative, make it positive and set the negative flag
        if(x < 0){
            x = abs(x);
            negative = true;
        }

        // Skip any trailing zeros by dividing x by 10 until the last digit is non-zero
        while(x % 10 == 0){
            x /= 10;
        }

        // Loop to reverse the digits of x
        while ( x != 0)
        {
            // Before multiplying by 10, check for overflow
            if(rev > INT_MAX / 10 || rev < INT_MIN / 10) return 0;

            temp = x % 10;  // Get the last digit
            rev = rev * 10 + temp;  // Append the digit to the reversed number
            x /= 10;  // Remove the last digit from x
        }

        // If the original number was negative, apply the negative sign to the reversed number
        if(negative) rev = -rev;

        return rev;  // Return the reversed number
    }
};
8400