3

The question I am trying to solve is:

Implement pow(x, n), which calculates x raised to the power n (Leetcode problem 50)

I have the following code:

class Solution {
 public:
  double myPow(double x, int n) {
    if (n == 0) {
      cout << "in last";
      return 1;
    } else if (n < 0) {
      x = 1 / x;

      return myPow(x, -n);
    } else if (n % 2 == 0) {
      double y;
      cout << "in even";
      y = myPow(x, n / 2);
      cout << "y is ";
      cout << y;
      return (y * y);

    }

    else {
      cout << "in odd";
      double j = myPow(x, n - 1);
      cout << "j is ";
      cout << x * j;
      return (x * j);
    }
  }
};

When ran for the test case x=1.00000 and n = -2147483648. I am getting the error:

runtime error: negation of -2147483648 cannot be represented in type 'int'; cast to an unsigned type to negate this value to itself (solution.cpp)

Why do I get this and how shall I solve it? TIA

David G
  • 94,763
  • 41
  • 167
  • 253
hydra123
  • 337
  • 5
  • 14
  • 4
    With a typical 2's complement signed integer type, the negative of the minimum value cannot be represented in the type's positive range. – Shawn Nov 16 '19 at 20:39

2 Answers2

1

If you want to support -2147483648 then you need to use a long long type, not an int.

If int is a 32 bit 2's complement type then 2147483648 is actually a long or a long long type.

There are no such things as negative literals in C++ (-2147483648 is a compile time evaluable constant expression consisting of the negation of the literal 2147483648), so -2147483648 is either a long or a long long type too. This is why you'll often see INT_MIN defined as -2147483647 - 1.

If the above is the case on your platform then the behaviour of your code is undefined for that input, as you are overflowing an int type.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
0
  • A 4 bytes (or 32 bits) int has a range of -2,147,483,648 to 2,147,483,647, thus if you negate -2,147,483,648 you can't represent it as int.
  • You could try using unsigned int (which has a range of 0 to 4,294,967,295) or long long int (which a range of -(2^63) to (2^63)-1) make this negation and fit the positive value there.

I opted for a different approach and handled this case separately since it is the only value that will cause us trouble.

  • Add 1 to that negative value before negating it.
  • To compensate for that I multiplicate the base once more separately.
if (n == -2,147,483,648)
{
    return (1.0/x) * myPow(1.0/x, -(n + 1));
}

The full solution

double myPow(double x, int n)
{
    if (n == 0) return 1.0;

    if (n < 0)
    {
        if (n == -2,147,483,648)
        {
            return (1.0/x) * myPow(1.0/x, -(n + 1));
        }

        return myPow(1.0/x, -n);
        }
        
    return (n % 2 == 0) ? myPow(x * x, n / 2) : x * myPow(x * x, n / 2);
}