分析
难度 中
来源
https://leetcode.com/problems/powx-n/
题目
Implement pow(x, n), which calculates x raised to the power n (xn).
Example 1:
Input: 2.00000, 10
Output: 1024.00000
Example 2:
Input: 2.10000, 3
Output: 9.26100
Example 3:
Input: 2.00000, -2
Output: 0.25000
Explanation:
Note:
- -100.0 < x < 100.0
- n is a 32-bit signed integer, within the range [−231, 231 − 1]
解答
Runtime: 12 ms, faster than 88.92% of Java online submissions for Pow(x, n).
1 package LeetCode; 2 3 public class L50_PowXN { 4 public double Pow(double x, int n) { 5 double result=1; 6 double temp=x; 7 String binN = Integer.toBinaryString(n); 8 int len=binN.length(); 9 //System.out.println(binN); 10 for(int i=0;i<len;i++){ 11 int pos=len-1-i; 12 //从低位到高位开始计算 13 if(binN.charAt(pos)=='1'){ 14 result*=temp;//指数位上的求和,相当于底数位上的乘积 15 } 16 temp*=temp;//当前位表示的大小 17 } 18 return result; 19 } 20 public double myPow(double x, int n) { 21 double result=0; 22 if(n==0) 23 return 1; 24 if(n<0) 25 result=1/Pow(x,-n); 26 else 27 result=Pow(x,n); 28 return result; 29 } 30 public static void main(String[] args){ 31 double x=2.0; 32 int n=-2; 33 L50_PowXN l50=new L50_PowXN(); 34 System.out.println(l50.myPow(x,n)); 35 } 36 }
Explanation: