0
点赞
收藏
分享

微信扫一扫

Day30 Pow(x, n)

实现 pow(x, n) ,即计算 x 的 n 次幂函数(即,x^n)

https://leetcode-cn.com/problems/powx-n/

示例1:

示例2:

示例3:

提示:

Java解法

package sj.shimmer.algorithm.ten_3;

/**
 * Created by SJ on 2021/2/23.
 */

class D30 {
    public static void main(String[] args) {
        System.out.println(myPow(-2.00000 ,2));
        System.out.println(myPow(2.0000, -2));
        System.out.println(myPow(2.0000, 10));
        System.out.println(myPow(2.1000, 3));
        System.out.println(myPow(1, 2147483647));
    }

    public static double myPow(double x, int n) {
        if (x==1) {
            return 1;
        }
        if (x==-1) {
            if (n%2==0) {
                return 1;
            }
            return -1;
        }
        if (x == 0) {
            return 0;
        }
        if (n == 0) {
            return x > 0 ? 1 : -1;
        }
        if (n == 1) {
            return x;
        }
        if (n == -1) {
            return 1/x;
        }
        boolean isPostive = n>0;
        int spilt = n / 2;
        double temp = myPow(x, spilt);
        double single = 1;
        if (n % 2!=0) {
           single =  myPow(x, n % 2);
        }
        x = temp*temp * single;

        return x;
    }
}

官方解

https://leetcode-cn.com/problems/powx-n/solution/powx-n-by-leetcode-solution/

  1. 快速幂 + 递归

    • 时间复杂度:O(logn)
    • 空间复杂度:O(logn)
  2. 快速幂 + 迭代

举报

相关推荐

【50】Pow(x,n)

Day30——快速排序

云计算day30

力扣 Pow(x,n)

Python 学习日记day30

LeetCode-050-Pow(x, n)

0 条评论