My writing method for this question may be different from that of others, and the overall thinking is the same.
The first step is to determine N, as shown in the code.
I want to convert exponential n to binary, for example, 3 ^ 45.
The binary value of 45 is 101101.
Scan from left to right and skip the first place.
If the bit is 0, the result is squared, that is, the result is multiplied by itself.
If the bit is 1, we need to multiply X in addition to the result square.
This principle is based on the exponential nature. If n = 10 (Binary), it is equivalent to 2. If n shifts one bit left, it is * 2, that is, 100 (Binary) that is, 4, multiplied by an X, which is equivalent
3 ^ 4*3 ^ 1 = 3 ^ 5-> 101 (Binary)
This method uses 2 as the base index square every time. It is often used in encryption algorithms because it is an exponential operation.
Based on the above rules, the result of 3 ^ 45 can be easily calculated.
public double pow(double x, int n) { if(n==1) return x; else if(n>1) { return pows(x,n); } else if(n==0){ return 1; } else { return (double)(1.0/pows(x,Math.abs(n))); } } public double pows(double x, int n){ String s=Integer.toBinaryString(n); double result=x; for(int i=1;i<=s.length()-1;i++){ char c=s.charAt(i); result=result*result; if(c=='1') result=result*x; } return result; }
[Leetcode] Pow (x, n)