Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Negating INT_MIN in CPP

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

like image 415
hydra123 Avatar asked Oct 19 '25 04:10

hydra123


1 Answers

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.

like image 60
Bathsheba Avatar answered Oct 21 '25 19:10

Bathsheba