Assignment:
Write a recursive function recPow that computes 2n for n >= 0 in Java. The function will have the following profile:
public static int recPow(int n)
The function must consider all cases and be tested exhaustively.
My Problem
I don't understand why my code returns -2147483648 when I enter recPow(31)
instead of 2147483648. I know some of you might tell me to switch to long instead of int, but I believe due to the assignment's verbiage I need to stick with int. I have never been very good computing numbers if any one can help me understand why this happens I would truly, greatly appreciate it.
Additionally - larger exponents return 0 (however I think this may have to do with the fact that we need to use ints vs longs.)
My Code
public static int baseNum = 2, powResult = 1;
public static int recPow(int n) {
//if the int is not bigger than 0
//must only accept ints
if (n < 0) {
throw new IllegalArgumentException("n has to be > 0");
} else {
//recursion here
//base number = 2
if (n==0) {
return powResult;
} else {
powResult = powResult * baseNum;
return recPow(n - 1);
}
}
}