0

I am doing a leetcode problem. https://leetcode.com/problems/powx-n/

Implement pow(x, n), which calculates x raised to the power n (i.e., x^n).

I have no idea why last test case is failing, x^-2147483648 returns 1 instead of 0.

  1. Why should this even return 0 in first place?
  2. Also, Math.abs(n) in debugger still returns a negative -2147483648.

--

Code:

class Solution {
    public double myPow(double x, int n) {
        if (n == 0)
            return 1;
        if (n < 0) {
            return 1 / getDFS(x, Math.abs(n));
        }
        return getDFS(x, n);
    }

    private double getDFS(double x, int n) {
        if (n == 1) {
            return x;
        }
        double saveData = 1;
        if (n / 2 >= 1) {
            int newN = n / 2;
            saveData = getDFS(x,newN);
        } 
        if (n % 2 == 1) {
            return saveData * saveData * x;
        }
        return saveData * saveData;
    }
}

Results:

enter image description here

mattsmith5
  • 540
  • 4
  • 29
  • 67
  • The problem is that `Math.abs(n)` doesn't always return a non-negative number. Try stepping through your code in a debugger or adding some `println` statements to see what the values of your variables are at each step. https://docs.oracle.com/en/java/javase/20/docs/api/java.base/java/lang/Math.html#abs(int) – kaya3 May 11 '23 at 03:02

1 Answers1

1

The magnitude of the smallest negative int value is larger than the magnitude of the largest positive int value. Thus Math.abs cannot return the correct value for Integer.MIN_VALUE.

To solve this problem, you can cast the exponent to long before using binary exponentiation.

public double myPow(double x, int n) {
    if (n == 0)
        return 1;
    if (n < 0) return 1 / getDFS(x, Math.abs((long) n));
    return getDFS(x, n);
}
private double getDFS(double x, long n) {
    // ...
    if (n / 2 >= 1) { 
        long newN = n / 2;
        saveData = getDFS(x,newN);
    }
    // ...
}
Unmitigated
  • 76,500
  • 11
  • 62
  • 80