Given an integer, write a function to determine if it is a power of two.
代码语言:javascript复制 public boolean isPowerOfTwo(int n) {
if (n <= 0) {
return false;
}
return (n & (n - 1)) == 0;
}
Implement pow(x, n).
代码语言:javascript复制 public double myPow(double x, int n) {
if (n < 0) {
return 1 / pow(x, -n);
} else {
return pow(x, n);
}
}
private double pow(double x, int n) {
if (n == 0) {
return 1;
}
double v = pow(x, n / 2);
if (n % 2 == 0) {
return v * v;
} else {
return v * v * x;
}
}
}