1.算法源码
package com.offer;
/**
* @authore Xavier
* @description 面试题16:数值的整数次方
* 题目:实现函数double Power(double base, int exponent),求base的exponent
* 次方。不得使用库函数,同时不需要考虑大数问题。
* @date 2018/7/26
*/
public class Power {
static double PowerWithUnsignedExponent(double base, int exponent) {
//判断底数为0,幂为负数
if (Double.doubleToLongBits(base) == Double.doubleToLongBits(0.0) && exponent < 0) {
return 0.0;
}
//判断是否为负数
boolean isNegtive = exponent >= 0 ? false : true;
int exponentAbs = exponent >= 0 ? exponent : 0 - exponent;
double result = recursion(base, exponentAbs);
if (isNegtive) {
result = 1.0 / result;
}
return result;
}
static double recursion(double base, int exponent) {
if (exponent == 0) {
return 1;
}
if (exponent == 1) {
return base;
}
//右移代替除2
double result = PowerWithUnsignedExponent(base, exponent >> 1);
result *= result;
//判断是否为奇数
if ((exponent & 0x1) == 1) {
result *= base;
}
return result;
}
}
2.Test Case
package com.offer;
import org.junit.Assert;
import org.junit.Test;
/**
* @author Xavier
* @description
* @date 2018/7/26
*/
public class PowerTest {
@Test
public void powerWithUnsignedExponent() throws Exception {
// 底数、指数都为正数
Assert.assertEquals(8, Power.PowerWithUnsignedExponent(2, 3), 0.00001);
// 底数为负数、指数为正数
Assert.assertEquals(-8, Power.PowerWithUnsignedExponent(-2, 3), 0);
// 指数为负数
Assert.assertEquals(0.125, Power.PowerWithUnsignedExponent(2, -3), 0);
// 指数为0
Assert.assertEquals(1, Power.PowerWithUnsignedExponent(2, 0), 0);
// 底数、指数都为0
Assert.assertEquals(1, Power.PowerWithUnsignedExponent(0, 0), 0);
// 底数为0、指数为正数
Assert.assertEquals(0, Power.PowerWithUnsignedExponent(0, 4), 0);
// 底数为0、指数为负数
Assert.assertEquals(0, Power.PowerWithUnsignedExponent(0, -4), 0);
}
}