剑指offer面试题16:数值的整数次方(java实现)

题目:实现函数double Power(double base,int exponent) 求base的exponent次方。不得使用库函数,同时不需要考虑大数问题;

public class PowerBySelf {
	public static void main(String[] args) {
		Double base =new Double("12"); //为了和0.0进行比较,进行装箱操作
		int exponent = 0;
		System.out.println(power(base,exponent));
	}
	static boolean g_invalidInput = false;	 //用来判断是否是无效输入
	public static double power(Double base, int exponent) {
		Double  checkBase = 0.0;
		if(base.compareTo(checkBase)==0||base<0) {   //compareTo(Double anotherDouble)返回0时表示相等
			System.out.println("底数不能为0");
			g_invalidInput = true;
			return 0;
		}
		if(exponent==0)
			return 1;
		int e = Math.abs(exponent);		//取绝对值
		for(int i=1;i<e;i++) {
			base *= base;
		}
		return exponent>0?base:1/base;
	}
}	

分析:因为用户输入的base可能是0,正数,负数。

1)当base是<0时,报错。

2)base==0时,用JavaDouble.compareTO()来表示两个Double数据进行比较。double x1== double x2 永远是false;

3)base>0时,一切正常。

exponent可能是0,正数,负数。

1)当exponent = 0时,我们返回1;

2)当exponent为负数时时,我们对其取绝对值,正常计算base值,读后返回1/base即可;

 

优化代码:

public class PowerBySelf {
	public static void main(String[] args) {
		Double base =new Double("3"); //为了和0.0进行比较,进行装箱操作
		int exponent = 5;
		System.out.println(power(base,exponent));
	}
	static boolean g_invalidInput = false;	 //用来判断是否是无效输入
	public static double power(Double base, int exponent) {
		Double  checkBase = 0.0;
		if(base.compareTo(checkBase)==0||exponent<0) {   //compareTo(Double anotherDouble)返回0时表示相等
			System.out.println("底数不能为0");
			g_invalidInput = true;
			return 0;
		}
		if(exponent==0)
			return 1;
		if(exponent==1)
			return base;
		double result = power(base, exponent>>1); //右移一位,相当于除以2;
		result *= result;
		if(exponent%2==1)   //用来判断是否为奇数
			result *= base;
		return result;
	}
}	

分析:我们将2^16 拆分为(2^2)^8 这样优化代码。每次exponent变为原来的二分之一,base = base*base; 结果不变. 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值