死磕算法系列文章
“Leetcode : https://leetcode-cn.com/problems/shu-zhi-de-zheng-shu-ci-fang-lcof
“GitHub : https://gitee.com/nateshao/leetcode/blob/main/algo-notes/src/main/java/com/nateshao/sword_offer/topic_13_myPow/Solution.java
题目描述:
实现 pow(x, n),即计算 x 的 n 次幂函数(即,x^n )。不得使用库函数,同时不需要考虑大数问题。
示例 1:
输入:x = 2.00000, n = 10
输出:1024.00000
示例 2:
输入:x = 2.10000, n = 3
输出:9.26100
示例 3:
输入:x = 2.00000, n = -2
输出:0.25000
解释:2^2 = 1/2^2 = 1/4 = 0.25
提示:
-100.0 < x < 100.0
-231 <= n <= 231-1
-104 <= xn <= 104
“快速幂实际上是二分思想的一种应用。
转化为位运算:
代码:
“Java 代码中 int32 变量 n 属于 n∈[−2147483648,2147483647] ,因此当 n = -2147483648时执行 n = -n会因越界而赋值出错。解决方法是先将 n 存入 long 变量 b ,后面用 b 操作即可。
package com.nateshao.sword_offer.topic_13_myPow;
/**
* @date Created by 邵桐杰 on 2021/11/21 10:48
* @微信公众号 程序员千羽
* @个人网站 www.nateshao.cn
* @博客 https://nateshao.gitee.io
* @GitHub https://github.com/nateshao
* @Gitee https://gitee.com/nateshao
* Description: 剑指 Offer 16. 数值的整数次方
* 实现 pow(x, n) ,即计算 x 的 n 次幂函数(即,xn)。不得使用库函数,同时不需要考虑大数问题。
*/
public class Solution {
public static void main(String[] args) {
double v = myPow1(2, 3);
System.out.println("v = " + v);
}
public static double myPow1(double x, int n) {
if (n == 0 || x == 1.0) return 1.0;
if (n == 1) return x;
if (n == -1) return 1.0 / x;
double res = myPow1(x, n / 2);
res = res * res;
//如果是奇数
if ((n & 1) == 1 && n > 0) res = res * x; // 就是判断奇偶,=1为奇数,比%效率更高
if ((n & 1) == 1 && n < 0) res = res * 1 / x;
return res;
}
public double myPow2(double x, int n) {
if (n == 0) return 1;
if (n == 1) return x;
if (n == -1) return 1 / x;
double half = myPow2(x, n >> 1); // n>>1就是n/2,但是右移效率更高
double rest = myPow2(x, n & 1);
return half * half * rest;
}
}
革命尚未成功,同志仍需努力,冲冲冲