[剣指Offer]数値の整数次(Java)
2809 ワード
剣指Offerテーマ
タイトルの説明
構想
コード#コード#
-- Offer 12
タイトルの説明
double base int exponent。 base exponent 。
構想
* 1、 , 13 1101。
* 2、 :10^1101 = 10^0001*10^0100*10^1000。
* 3、 &1 >>1 1101, 1 。
コード#コード#
package com.my.test.codinginterviews.other;
/**
* :
* -- Offer 12
*
* :
* double base int exponent。 base exponent 。
*/
public class Power
{
/**
* :
* 1、 , 13 1101。
* 2、 :10^1101 = 10^0001*10^0100*10^1000。
* 3、 &1 >>1 1101, 1 。
*/
public double power(double base, int exponent) {
if (exponent == 0) {
return 1;
}
double res = 1, cur = base;
boolean isExpPositive = exponent > 0;
if (!isExpPositive) {
if(base == 0) {
throw new RuntimeException("invalid param");
}
exponent = -exponent;
}
while(exponent != 0){
if ((exponent & 1) == 1)
res *= cur;
cur *= cur;
exponent >>= 1;
}
return isExpPositive ? res : (1/res);
}
/**
* :
* n ,a^n=a^n/2*a^n/2;
* n ,a^n=(a^(n-1)/2)*(a^(n-1/2))*a
* O(logn)
*/
public double powerII(double base, int exponent) {
int n = Math.abs(exponent);
if (n == 0) {
return 1;
}
if (n == 1) {
return base;
}
double result = powerII(base, n >> 1);
result *= result;
// base
if ((n & 1) == 1) {
result *= base;
}
if (exponent < 0) {
result = 1 / result;
}
return result;
}
/**
* ( , o(n)):
* 1、
* 2、 exp 0, 1
* 3、 exp , base*base*...(exp )
* 4、 exp , 1/base*1/base*...(exp )
*/
public double powerIII(double base, int exponent) {
if (exponent > 0) {
return base * powerIII(base, exponent - 1);
} else if(exponent < 0) {
return (1/base) * powerIII(base, exponent + 1);
} else {
return 1;
}
}
public static void main(String[] args)
{
Power p = new Power();
System.out.println(p.power(1.2d, 2));
System.out.println(p.power(1.2d, 0));
System.out.println(p.power(1.2d, -2));
System.out.println(p.powerII(1.2d, 2));
System.out.println(p.powerII(1.2d, 0));
System.out.println(p.powerII(1.2d, -2));
}
}