I need to write a method in java to return the power of only integer number and i want this method to return -1 or fire exception if the number exceeds the Integer.MAX_VALUE:
I tried the first and easy step:
public static int GetPower(int base, int power)
{
int result = 1;
for(int i = 1; i<=power; i++)
{
result *= base;
if (result < 0 ) {
break; // not very acurate
}
}
if (result < 0 ) {
return -1;
}
return result;
}
Is the above method accurate, as after debugging i found that when the result exceeds the Integer.MAX_VALUE it will go to negative number, or there is another way to handle this?
A power of 10 is as many number 10s as indicated by the exponent multiplied together. Thus, shown in long form, a power of 10 is the number 1 followed by n zeros, where n is the exponent and is greater than 0; for example, 106 is written 1,000,000.
Following are detailed step. 1) Initialize pow = x, i = 1 2) while (pow < y) { pow = pow*pow i *= 2 } 3) If pow == y return true; 4) Else construct an array of powers from x^i to x^(i/2) 5) Binary Search for y in array constructed in step 4. If not found, return false. Else return true.
Your method will work if the base can only be positive integer. Underflow might occur your base is a negative integer and your power is an odd number.
An easy but not optimal way to handle this situation is to use long data type to store the output and compare the output to check whether it is between Integer.MAX_VALUE and Integer.MIN_VALUE.
public static int GetPower(int base, int power){
long result = 1;
for(int i = 1; i <= power; i++)
{
result *= base;
if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) {
return -1;
}
}
return result;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With