Pow(x, n)

来源:互联网 发布:2016nba西决数据统计 编辑:程序博客网 时间:2024/06/07 09:30

50. Pow(x, n)

 
 My Submissions
  • Total Accepted: 98575
  • Total Submissions: 356042
  • Difficulty: Medium

Implement pow(xn).

Subscribe to see which companies asked this question

Show Tags
Show Similar Problems
Have you met this question in a real interview? 
Yes
 
No

Discuss Pick One


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));}}


0 0