When it comes to the operation of power exponents, we will use Math.pow(doublea, doubleb), and the result returned is to the power of a.
In Java, when we calculate the n-power of 2, we can directly use Math.pow to calculate. Very convenient.
However, it is known that the result of a power is M and the base number a of the power, and now requires the exponent n of the power. The log(double) method provided in Math, but only one parameter is passed in, namely M. So the question is, how to meet our requirements simply, conveniently and quickly? The answer is as follows:
n=Math.log(M)/Math.log(a);
This method can satisfy most of our power index calculations, but the value accessed and the value passed in each time are double. What should I do if I don’t want to transfer it? We have a new solution.
Solution premise: The base number of the power index is a multiple of 2.
Here we use shift operation (shift operation is based on binary, so the prerequisite for the solution is this basis). If we find the power of 2 to 3, we can use 2<<(3-1) to calculate the result.
To the 2nd power of 4, we must first convert 4 into the 2nd power of 2, and then use 2<<(4-1) to calculate the result.
The effect of the following method is to pass in two numbers added to a multiple of 2, such as 12 (4+8), and we automatically calculate it [4,8]
For example, 18, we calculate it [2, 16]
For example, 22, we calculate it [2, 4, 16]
/** * Convert to an integer array starting at the power of 2, string array* @param sum The value of the incoming faction can be the value of a faction or the value added to multiple factions* 2^1 + 2^2 This * Suddenly forgetting the shift operation is also an exponential power operation* @return */private static int[] toUgroupArray(int sum){if(sum < 0){System.out.println("you have an eraor code");} else if(sum == 0) {System.out.println("you have no choice code");} else{String binaryCode = Integer.toBinaryString(sum);System.out.println("binary code:"+binaryCode);int index = binaryCode.length() -1;String str = "";for (int i=0;i<binaryCode.length();i++){if(binaryCode.charAt(i) == '1'){str = str + index +",";}index --;}str = str.substring(0, str.length()-1);System.out.println(str);String[] strArray = str.split(",");int[] result = new int[strArray.length];//You can also return a character array//String[] result2 = new String[strArray.length]; for (int i=0;i<strArray.length;i++){//result[i] = (int)Math.pow(2, Double.parseDouble(strArray[i])); result[i] = 2 << (Integer.parseint(strArray[i])-1);}return result;}return null;}Summarize
The above is all the content of this article about the operation code analysis of the power index value in Java, and I hope it will be helpful to everyone. Interested friends can continue to refer to other related topics on this site. If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!