Skip to content

Instantly share code, notes, and snippets.

@HDegano
Created May 27, 2015 16:51
Show Gist options
  • Save HDegano/63e682916560a677e0ad to your computer and use it in GitHub Desktop.
Save HDegano/63e682916560a677e0ad to your computer and use it in GitHub Desktop.
Implement pow(a, b) logN
public class Pow {
public double myPow(double x, int n) {
boolean isNegative = n < 0;
if(isNegative)
n = n * -1;
double result = innerPow(x, n);
if(isNegative)
return 1 / result;
return result;
}
private double innerPow(double a, int b){
if(a == 0) return 0;
if(a == 1 || b == 0) return 1;
if(b == 1) return a;
double result = innerPow(a, b / 2);
result = result * result;
if((b & 1) === 1)
result = result * a;
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment