Pow(x, n)

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值