题目地址:
https://leetcode-cn.com/problems/shu-zhi-de-zheng-shu-ci-fang-lcof/
思路
方法一:暴力法
方法二:利用指数法则递归计算(分奇数和偶数)
还没搞懂
方法三: 将n表示为二进制来做
package jzoffer;
/**
* @Auther: wwh
* @Date: 2020-04-12 15:48
* @Description:
*/
public class MyPow {
/*
*
* @date: 2020-04-12 16:03
* @param: * @param null:
* @return: * @return: null
* @author: wwh
* @Description:暴力
时间复杂度:O(n)O(n). 我们需要将 x 连乘 n 次。
空间复杂度:O(1)O(1). 我们只需要一个变量来保存最终 x 的连乘结果。
*/
public double foolPow(double x, int n) {
if(n<0){
n= -n;
x = 1/x;
}
double ans = 1;
for (int i = 0; i < n; i++) {
ans = ans*x;
}
return ans;
}
/*
*
* @date: 2020-04-12 16:12
* @param: * @param null:
* @return: * @return: null
* @author: wwh
* @Description: 快速幂
* 最小值:Integer.MIN_VALUE= -2147483648 (-2的31次方)
最大值:Integer.MAX_VALUE= 2147483647 (2的31次方-1)
这里需要使用long类型,因为如果传入的n = -2147483648; 那么转成正数就丢失,所以要使用long
*/
public double fastPow(double x,long n){
if(n==0){
return 1;
}
double half = fastPow(x,n/2);
if(n%2==0){
return half*half;
}else {
return half*half*x;
}
}
public double myPow2(double x, int n) {
long N = -n;
if (n < 0) {
x = 1 / x;
N = -N;
}
return fastPow(x, N);
}
/**
*
* @date: 2020-04-12 22:28
* @param: * @param x:
* @param n:
* @return: * @return: double
* @author: wwh
* @Description: 非递归实现
*/
public double myPow3(double x, int n) {
long N = n;
if (N < 0) {
x = 1 / x;
N = -N;
}
double ans = 1;
double current_product = x;
for (long i = N; i > 0; i >>=1) {
if ((i&1)==1 ) {
ans = ans * current_product;
}
current_product = current_product * current_product;
}
return ans;
}
/**
*
* @date: 2020-04-12 23:58
* @param: * @param null:
* @return: * @return: null
* @author: wwh
* @Description:
* 作者:liweiwei1419
* 链接:https://leetcode-cn.com/problems/shu-zhi-de-zheng-shu-ci-fang-lcof/solution/di-gui-xie-fa-fen-zhi-si-xiang-yu-fei-di-gui-xie-f/
* 来源:力扣(LeetCode)
* 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
*/
public class Solution {
public double myPow(double x, int n) {
long N = n;
if (N < 0) {
x = 1 / x;
N *= -1;
}
double res = 1;
while (N > 0) {
if ((N % 2) == 1) {
res *= x;
}
x *= x;
N /= 2;
}
return res;
}
}
public static void main(String[] args) {
//MyPow myq= new MyPow();
//System.out.println(myq.myPow3(2, -2));
int n = 10;
System.out.println(n/=2);
}
}