数值的整数次方

19 篇文章 0 订阅
19 篇文章 0 订阅

剑指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);
	}

}






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值