剑指offer第十一题,就是实现java中的库函数pow(double base,int exp),得考虑非法输入以及指数为负的情况
package com.zjy.sword2offer;
public class Power {
public static double power(double base, int exponent) throws Exception{
if(base==0.0 && exponent<0)
new Exception("invalid input.");
int exp = Math.abs(exponent);
double result = 1.0;
for(int i=1;i<=exp;i++)
{
result *= base;
}
if(exponent<0)
result = 1/result;
return result;
}
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
double res = power(0,-3);
System.out.println(res);
}
}
测试的时候发现我对非法输入设置的异常没有作用,后来发现是因为浮点数有误差,用base==0.0的判断是没法生效的,修改后的代码为
package com.zjy.sword2offer;
public class Power {
public static double power(double base, int exponent) throws Exception{
if(equal(base,0.0) && exponent<0)
throw new Exception("invalid input.");
int exp = Math.abs(exponent);
double result = 1.0;
for(int i=1;i<=exp;i++)
{
result *= base;
}
if(exponent<0)
result = 1/result;
return result;
}
public static boolean equal(double val1, double val2){
if((val1-val2>-0.000001) && (val1-val2<0.000001))
return true;
else
return false;
}
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
double res = power(0,-3);
System.out.println(res);
}
}
以上算法的复杂度为O(n),还可以降低,利用一个数的8次方可以由他的4次方相乘,能够将复杂度降低到O(logn)
package com.zjy.sword2offer;
public class Power {
public static double power(double base, int exponent) throws Exception{
if(equal(base,0.0) && exponent<0)
throw new Exception("invalid input.");
int exp = Math.abs(exponent);
double result = 1.0;
result = multiply(base,exp);
if(exponent<0)
result = 1/result;
return result;
}
public static boolean equal(double val1, double val2){
if((val1-val2>-0.000001) && (val1-val2<0.000001))
return true;
else
return false;
}
public static double multiply(double a, int b){
if(b==0)
return 1;
if(b==1)
return a;
double result = multiply(a,b>>1);
result *= result;
if((b&1)==1)
result *= a;
return result;
}
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
double res = power(2,10);
System.out.println(res);
}
}