Leetcode 50. Pow(x, n) [medium][java]

Implement pow(x, n), which calculates x raised to the power n (x^n).

Example
在这里插入图片描述

Solution 1
Consideration

  1. divide n by 2, and recursively call the function
  2. if n is Integer.MIN_VALUE, n = -n will overflow. So we let n/2 be -n/2. Then let x be 1/x.
class Solution {
    public double myPow(double x, int n) {
        if(n == 0)
            return 1;
        if(n == 1)
            return x;
        int t = n/2;
        if(n < 0) {
            t = -t;
            x = 1/x;
        }
        
        double res = myPow(x, t);
        if(n%2 == 0) return res*res;
        return res*res*x;
    }
}

Solution 2
Consideration

  1. if we use binary to represent n. We should only consider the positions where the digit is 1.
  2. We use this to divide n to several numbers to multiply.
class Solution {
    public double myPow(double x, int n) {
        // if n = Integer.MIN_VALUE, -n will overflow. So if n < 0, we decrease -n by 1.
        int m = n < 0 ? -n - 1 : n;
        double p = 1;
        for(double q = x; m > 0; m/=2) {
            if((m & 1) == 1)
                p *= q;
            q *= q;
        }
        
        return n < 0? 1/p/x: p;
    }
}

Reference

  1. https://blog.csdn.net/happyaaaaaaaaaaa/article/details/51655964
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值