I'd try to make your code more readable by giving a meaningful name to the variables you use. What about changing the signature of your method to
public static double exponentiate(double base, int exponent)
I think it is worth it, even if you're implementing a simple mathematical function like this one.
I'd also try to make it clear what you're doing with the ((y >> i) & 1) == 1
expression. What about introducing an isBitSet
variable? I think introducing it (or an equivalent bool isByteSet(int number, int position)
function) would make your code more readable. I'd also rename part
to something like candidateFactor
, which would make it clear that you're computing the factor corresponding to each binary digit and deciding whether to use it or not according to isBitSet
.
I'd also recommend you to do some validation of your input values. What happens if you get passed a negative value for exponent
?
You can either make it an exceptional case and throw an IllegalArgumentException
or handle it knowing that x^y = 1/(x^(-y))