Java程序用于快速求幂
package Solution50;
class Solution {
public double myPow(double x, int n) {
boolean minus = false;
if (n < 0)
minus = true;
long b = Math.abs((long) n);
double res = 1;
while (b > 0) {
if ((b & 1) == 1)
res *= x;
x *= x;
b >>= 1;
}
if (minus)
return 1 / res;
else
return res;
}
public static void main(String[] args) {
Solution sol = new Solution();
double x = 2.10000;
int n = 3;
System.out.println(sol.myPow(x, n));
}
}
package SolutionOffer16;
class Solution {
public double myPow(double x, int n) {
double exp = n;
if (exp < 0) {
x = (1 / x);
exp = -exp;
} else if (exp == 0) {
return 1;
}
double y = 1;
while (exp > 1) {
if (exp % 2 == 0) {
x = x * x;
exp = exp / 2;
} else {
y = x * y;
x = x * x;
exp = (exp - 1) / 2;
}
}
return x * y;
}
public static void main(String[] args) {
Solution sol = new Solution();
double x = 2.10000;
int n = 3;
System.out.println(sol.myPow(x, n));
}
}