The sword refers to offer-11-integer power of numerical value-java

Questions and Tests

package sword011;
/* 问题描述:实现函数double power(double base,int exponent),求base的exponent次方。不能使用库函数,同时不需要考虑大数问题。
*/


public class main {
	
	public static void main(String[] args) {
		double [] testTable = {1,2,2.1};
		int [] testTable2 = {4,9,15};
		for(int i=0;i<testTable.length;i++){
			test(testTable[i],testTable2[i]);
		}
	}
		 
	private static void test(double ito,int ito2) {
		Solution solution = new Solution();
		double rtn;
		long begin = System.currentTimeMillis();
		System.out.print(ito+"  ");
		System.out.print(ito2);
		System.out.println();
		//开始时打印数组
		
		rtn= solution.power(ito,ito2);//执行程序
		long end = System.currentTimeMillis();	
		
		System.out.println("rtn=" );
		System.out.print(rtn);	
		System.out.println();
		System.out.println("耗时:" + (end - begin) + "ms");
		System.out.println("-------------------");
	}

}

Solution 1 (success)

First, consider the positive and negative of the exponet, and set the isPrime attribute, which is used for the final result = 1/result
. Second, a^b = a^c * a^(bc)
Using the binary method, the positive and negative of the exponet will be expanded in binary. , for example, to find 25, where 5=101(2)=1∗22+0∗21+1∗20, so 25=21∗22+0∗21+1∗20=51∗22∗50∗21∗51∗ 20
It can be seen from the above example that the positive and negative values ​​of exponet can be written in binary. When the corresponding bit is 1, it is multiplied by the current value, otherwise it is not multiplied;
the current value is 1, 2, 4, and 8 of base. . times, powerBase*powerBase can

Refer to  https://blog.csdn.net/xushiyu1996818/article/details/86607288

package sword011;


public class Solution {
	public double power(double base, int exponet) {
		if(exponet == 0) {
			return 1;
		}
		if(exponet == 1) {
			return base;
		}
		if(exponet == -1){
			return 1/base;
		}
		if(base == 0) {
			return 0;
		}
		// exponet是否为正
		boolean isPrime = true;
		if(exponet < 0) {
			isPrime = false;
			exponet = -exponet;
		}
		// 2的i次方
		int power2 = 1;
		// basek 的2的i次方
		double powerBase = base;
		double result = 1;
		while(exponet != 0) {
			if((exponet & power2) != 0) {
				result = result * powerBase;
				exponet = exponet - power2;
			}
			power2 = power2 << 1;
			powerBase = powerBase * powerBase;
		}
		if(!isPrime) {
			result = 1/result;
		}
		return result;
	}
}

 

 

Guess you like

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