LeetCode Top Interview Questions 50. Pow(x, n) (Java版; Medium)
题目描述
Implement pow(x, n), which calculates x raised to the power n (x^n).
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: 2-2 = 1/22 = 1/4 = 0.25
classSolution{publicdoublemyPow(double x,int n){if(x==0){return0;}if(x==1){return1;}//if(n==0){return1;}if(n==1){return x;}//double res =0;if(n<0){if(n==Integer.MIN_VALUE){
n++;
n =-n;//Integer.MAX_VALUE
x =1/x;return x*x *myPow(x*x, n/2);}else{
n =-n;
x =1/x;}}return n%2==0?myPow(x*x, n/2): x*myPow(x*x, n/2);}}
classSolution{publicdoublemyPow(double x,int n){long N = n;if(N <0){
x =1/ x;
N =-N;}double ans =1;double current_product = x;for(long i = N; i >0; i /=2){if((i %2)==1){
ans = ans * current_product;}
current_product = current_product * current_product;}return ans;}};
LeetCode Top Interview Questions 50. Pow(x, n) (Java版; Medium)
welcome to my blogLeetCode Top Interview Questions 50. Pow(x, n) (Java版; Medium)题目描述Implement pow(x, n), which calculates x raised to the power n (x^n).Example 1:Input: 2.00000, 10Output: 1024...