50. Pow(x, n)
- Total Accepted: 98575
- Total Submissions: 356042
- Difficulty: Medium
Have you met this question in a real interview?
Yes
No
package com.lp;
public class Solution {
public double myPow(double x, int n) {
if(n==0) return 1;
if(x==1) return 1;
long nn=(long)n;
if(n<0) {
nn=-1l*n;//注意别漏了l,-1*-2147483648=-2147483648
x=1/x;
}
return myPositivePow(x, nn);
}
/*
* 如:2^5,普通循环乘2,要循环五次。
* 如下只需要log5+1.
* 0000,0101
*/
public double myPositivePow(double x,long n){
double sum = 1;
double pre = x;
while(n!=0){
if((n&1)==1) {
sum=sum*pre;//如果当前位为1,需要累乘起来。
}
pre=pre*pre;//翻倍增长
n=n>>1;
}
return sum;
}
public static void main(String[] args) {
Solution solution = new Solution();
System.out.println(solution.myPow(2, -2147483648));
}
}