【剑指offer】16. 数值的整数次方

108 阅读1分钟

题目描述

在这里插入图片描述

在这里插入图片描述

// 力扣
// 实现函数double Power(double base, int exponent),
// 求base的exponent次方。不得使用库函数,同时不需要考虑
// 大数问题。

 
// 牛客
// 给定一个double类型的浮点数x和int类型的整数exponent。
// 求x的exponent次方。
// 保证x和exponent不同时为0

题解

// 直接法 //

// 牛客
// 运行时间:27ms
// 占用内存:10648k
public class Solution {
    public double Power(double x, int n) {
        if (x == 0)
            return 0;
        if (n == 0)
            return 1;
        if (n == 1)
            return x;

        if (n > 0) {
            double res = x;
            for (int i = 1; i < n; i++)
                res *= x;
            return res;
        }
        else {
            double res = 1/x;
            for (int i = 1; i < -n; i++)
                res *= 1/x;
            return res;
        }
	}
}
// 分治算法
// n个x相乘:x*x*...*x(n个)
// 其实可以分成(x*x*...*x)*(x*x*...*x)
// 				 (n/2个)     (n/2个)
// 以此类推,可以一直分下去,每次分治都减少一半。
// 需要特别注意的是,如果n是偶数直接分治就行。
// 如果n是奇数,还需要多乘一个x。

// 力扣
// 执行用时:1 ms, 在所有 Java 提交中击败了96.53%的用户
// 内存消耗:38.2 MB, 在所有 Java 提交中击败了5.87%的用户
public class Solution {
	public double Power(double x, int n) {
		if (x == 0) return 0;
			
		double res = 0;
		if (n > 0) {
			res = pow(x, n);
		}
		else {
			res = pow(1/x, n);
		}
		return res;
	}

	// 分治法n次方计算函数
	// 将n个x相乘,分为两个n/2个x相乘
	// 输入变量为:基数x,幂次n
	private double pow(double x, int n) {
		if (n == 0) return 1;  // 若n==0,返回1
		if (n == 1) return x;  // 若n==1,返回x,递归终止
		// 递归调用分治法函数,继续顺延分治计算,直到n为1
		double res = pow(x, n/2);  
		res = res * res;  // 实现分治逻辑,得到的res合并相乘
		if (n % 2 != 0)  // 如果是奇数(无法被2整除)
			res *= x;  // 多乘一个x
		return res;  // 最后返回res
	}
}

// 牛客
// 运行时间:22ms
// 占用内存:10652k
public class Solution {
    public double Power(double x, int n) {
        if (x == 0) return 0;

        double res = 0;
        if (n > 0) {
            res = pow(x, n);
        }
        else {
            res = pow(1/x, n);
        }
        return res;
    }

    private double pow(double x, int n) {
        if (n == 0) return 1;
        if (n == 1) return x;
        double res = pow(x, n/2);
        res = res * res;
        if (n % 2 != 0)  // 如果是奇数(无法被2整除)
            res *= x;
        return res;
    }
}