7. Reverse Integer

7. Reverse Integer

Problem statement:

Link to question

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

Code:

class Solution {
public:
    int reverse(int N) {
        long rev_num = 0, digit, temp;

        while(N){
            digit = N % 10;
            //Extracting unit digit and joining from the end by multiplying with 10.
            temp = (rev_num * 10) + digit;
            if (temp / 10 != rev_num)
                return 0;
            if ((rev_num > 0 && rev_num > (INT_MAX - digit)/10) || (rev_num < 0 && rev_num < (INT_MIN - digit)/10)) 
                return 0;
            rev_num = temp;
            N /= 10;
        }
        return rev_num;
    }
};

Explanation:

Here is a detailed explanation of each step:

  1. Initialize a long-type variable rev_num to store the reversed integer.

  2. The while loop continues as long as N is not 0.

  3. In each iteration, the last digit of N is extracted using the modulo operator % 10.

  4. The extracted digit is added to the rev_num by multiplying it by 10 and then adding the extracted digit. This is done by first creating a temporary variable temp equal to rev_num * 10 + N % 10.

  5. The code checks for overflow by comparing temp / 10 with rev_num. If they are not equal, it means the reversed integer has overflowed the range of the int type, and the function returns 0.

  6. If there is no overflow, rev_num is updated to temp and N is updated to N / 10 to remove the last digit.

  7. The while loop continues until N becomes 0.

  8. Finally, the reversed integer is returned as the result of the function.

Note: It's important to use a long type variable to store the reversed integer as the int type may overflow if the input integer is very large.

Summary:

The code uses a while loop to extract the last digit of the input integer N by using the modulo operator % 10 and adds it to the result rev_num after multiplying by 10. It checks for overflow by comparing temp / 10 with rev_num and returns 0 if they are not equal. After each iteration, N is updated to N / 10 to remove the last digit.

Thank you for taking the time to read my article. I look forward to continuing to share my writing with you and hearing more of your thoughts and opinions.

Happy learning!