题目
实现函数double Power(double base, int exponent),求base的exponent次方。不得使用库函数,同时不需要考虑大数问题。
分析
代码实现
public class Solution {
public static void main(String[] args) {
Solution15 s = new Solution15();
System.out.println(s.Power(2.00000, -2147483648));
}
/**
* 数值的整数次方
* @param base 底数
* @param exponent 指数
* @return
*/
public double Power(double base, int exponent) {
//主要是解决-2147483648的绝对值问题,
//long e = Math.abs((long)exponent);
if (base == 0 && exponent < 0){
return 1/base;//正无穷
}
double res = 1;
for (int i = 0; i < Math.abs(exponent); i++){
res *= base;
}
if (exponent < 0){
res = 1 / res;
}
return res;
}
}
分析
代码实现
public class Solution {
public static void main(String[] args) {
Solution15 s = new Solution15();
System.out.println(s.Power(2.00000, -2147483648));
}
/**
* 数值的整数次方
* @param x 底数
* @param n 指数
* @return
*/
public double Power(double x, int n) {
long e = Math.abs((long)n);
double res = mutiply(x, e);
if (n < 0){
res = 1/res;
}
return res;
}
public double mutiply(double x, long n) {
if (n == 0){
return 1;
}
if (n == 1){
return x;
}
double res = mutiply(x,n/2);
res *= res;
if (n % 2 == 1){
res *= x;
}
return res;
}
}
分析
代码
public class Solution {
public static void main(String[] args) {
Solution15 s = new Solution15();
System.out.println(s.myPower(2.00000, -2147483648));
}
/**
* 数值的整数次方
* @param x 底数
* @param n 指数
* @return
*/
public double myPower(double x, int n) {
if (x == 0){
return 0;
}
long e = Math.abs((long)n);
double res = 1;
while (e > 0){
//判断最后一位 如果是1 则表明bm为1 则2的次方有作用
if ((e & 1) == 1){
res *= x;
}
x *= x;
//右移一位
e >>= 1;
}
if (n < 0){
res = 1 / res;
}
return res;
}
}