The sword refers to offer--11. The integer power of the value

Topic: Implement a function to find the exponent power of base, do not use library functions, and do not need to consider the problem of large numbers

Idea: First of all, pay attention to consider comprehensively

    1. When the base is 0 and the exponent is less than 1, if the reciprocal is calculated, it will be an error and need to be processed

    2. Determine whether the base is 0. Since the base is double, you cannot directly use == to judge

Secondly, in addition to the general use of successive multiplication, you can also use a more efficient method, that is, think in a different way: to find the 32nd power of an integer, if the 16th power is known, you only need to square it on the basis of the 16th power, The 16th power is the square of 8, and so on, that is, we can solve it with the following formula:


public class wr11Power {
	static boolean flag=false;
	public static double Power(double base,int exponent){
//		如果底数为0,且指数小于0,则求解时是出错的,返回0
		if(equal(base,0.0)&&exponent<0){
			flag=true;
			return 0.0;
		}
		int absexponent=exponent;
		if(exponent<0){
			absexponent=-exponent;
		}
//		double res=getPower(base,absexponent);
		double res=getPowerBetter(base,absexponent);
		if(exponent<0){
			res=1.0/res;
		}
		return res;
	}
//	计算机内表示小数时(包括float和double)都有误差,因此不能用=判断,要看它们之差的绝对值是否在一个很小的范围内
	public static boolean equal(double num1,double num2){
		if(num1-num2>-0.0000001 && num1-num2<0.0000001){
			return true;
		}
		else{
			return false;
		}
	}
//	采用逐次相乘
	public static double getPower(double base,int e){
		double result=1.0;
		for(int i=1;i<=e;i++){
			result=result*base;
		}
		return result;
	}
//	公式递归求解
	public static double getPowerBetter(double base,int e){
		if(e==0){
			return 1.0;
		}
		if(e==1){
			return base;
		}
//		细节,用右移运算符代替了除以2,因为位运算的效率比乘除法及取余运算的效率要高很多
		double result=getPowerBetter(base,e>>1);
		result=result*result;
		if((e&1)==1){
			result=result*base;
		}
		return result;
	}
	
	public static void main(String [] args){
		System.out.println(Power(2,3));
	}

}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324126910&siteId=291194637