Created
May 27, 2015 16:51
-
-
Save HDegano/63e682916560a677e0ad to your computer and use it in GitHub Desktop.
Implement pow(a, b) logN
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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