LeetCode Reverse Integer

 Problem Description: https://leetcode.com/problems/reverse-integer/description/


Accepted Solution

/*

I have learned some crucial things during solving the problem. For example,

if you want to check integer overflows for several operations, you have to manage the following conditions:

  • int a = <something>; int x = <something>;
  • if (x < 0 && a > INT_MAX + x) // a - x would overflow // `a - x` would overflow
  • if (x > 0 && a < INT_MIN + x) // a - x would underflow
  • if (a == -1 && x == INT_MIN) // a * x can overflow
  • if (x == -1 && a == INT_MIN) // a * x (or a / x) can overflow
  • if (x != 0 && a > INT_MAX / x) // a * x would overflow
  • if (x != 0 && a < INT_MIN / x) // a * x would underflow
Hence, check the appropriate conditions in perfect positions at your code. Also, keep your attention when you are dealing with a negative number. Moreover, a negative number is unsuitable for direct calculation or dividing by 10. Therefore, when the 'x' is negative but less than INT_MAX, in that case, make it positive first, reverse the digits and return finally it as a non-positive value.

*/

class Solution {
public:
const int high = 1 << 31 - 1;
int power(int p)
{
    int res = 1;
    for(int i=0; i<p; i++)
    {
        res *= 10;
    }

    //cout << "res = " << res << "\n";

    return res;
}
int reverse(int x) {
    int ar[15], len=0, p, q;
    //cout << "Enter x: ";
    //cin >> x;
    //x = (1 << 31)-1;
    //cout << "main = " << x << "\n";
    bool negative = false;
    bool overflow = false;
    if(x < 0)
    {
        negative = true;
        p = -1;
        q = x;
        if(p == -1 && q == INT_MIN) // if negative a*x is overflow
        {
            overflow = true;
        }
        else
        {
            x = x * (-1);
        }

        //cout << x << " " << overflow << "\n";
    }
    while(x > 0)
    {
        ar[len++] = x % 10;
        x /= 10;
    }
    //for(int i=0; i<len; i++) cout << ar[i] << " ";
    int num = 0;
    for(int i=0, j=len-1; i<len; i++, j--)
    {
        p = ar[i];
        q = power(j);
        if(p != 0 && q > INT_MAX / p) // if p * q is overflow
        {
            overflow = true;
            break;
        }
       
        int t = p * q;

        if(num > 0 && t > INT_MAX - num) // if a + x is overflow
        {
            overflow = true;
            break;
        }

        num = num + t;
    }

    if(overflow)
    {
        return 0;
        //cout << 0 << "\n";
    }

    else
    {
        if(negative)
        {
            //cout << "-" << num << "\n";
            num = num * (-1);
            //cout << num << "\n";
            return num;
        }
        else
        {
            //cout << num << "\n";
            return num;
        }
    }
}
};

Comments

Popular posts from this blog

SPOJ-CMG - Collecting Mango

LightOJ 1009 - Back to Underworld

LeetCode Palindrome Number