Skip to content

Instantly share code, notes, and snippets.

@guolinaileen
Last active March 29, 2020 23:17
Show Gist options
  • Save guolinaileen/5054006 to your computer and use it in GitHub Desktop.
Save guolinaileen/5054006 to your computer and use it in GitHub Desktop.
binary strategy: 2^n=2^(n/2) * 2^(n/2) * 2^(n%2)
public class Solution {
public double pow(double x, int n) {
// Start typing your Java solution below
// DO NOT write main() function
if(n==0) return 1;
if(x==0) return 0;
if(n==1) return x;
if(n<0)
{
n=-n; x=1/x;
}
double half=pow(x, n/2);
double result=half*half*pow(x, n%2);
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment