当前位置:网站首页>实现pow(x,n)函数
实现pow(x,n)函数
2022-07-01 03:13:00 【热心市民薛先生】

本题不能使用for循环然后相乘,会超时。本题使用了快速幂法。
利用二进制与十进制转化的方法,把n拆开。

简单来说就是,n每次右移一位,x每次与自身相乘,当n的最右边为1时,res = res * x;
如x^10^用上述方法计算:
10的二进制是1010 记录结果res = 1
1、1010右边为0,所以不进行计算,然后1010右移变为101,x = x*x,变为x的平方
2、101最右为1,计算 res = res * x; 即res = x的平方,101右移为10,x = x*x ,此时x为初始x的4次方
3、10最右为0,不计算,右移变为1,x = x*x;x为初始值的8次方
4、1最右为1,计算res = res * x;即res = x的平方 * x的8次方, 1右移为0, x = x * x
5、结束
从上述的步骤来看,就是把x的10次方变为x的8次方和x的平方相乘
每次循环都更新x的值为x的平方,x依次为1次方2次方4次方8次方16次方.....当n最右侧为1时,再记录此时与x的乘积。
public double myPow(double x, int n) {
if(x==0) return 0;
long b = n;
double res = 1;
if(b<0){
x = 1/x;
b = -b;
}
while(b>0){
if((b&1)==1) res *= x;
x *= x;
b >>= 1;
}
return res;
}
Java 代码中 int32 变量 n \in [-2147483648, 2147483647]n∈[−2147483648,2147483647] ,因此当 n = -2147483648 n=−2147483648 时执行 n = -n ,n=−n 会因越界而赋值出错。解决方法是先将 n 存入 long 变量 b ,后面用 b 操作即可。
边栏推荐
- 访问url 404 的错误
- [small program project development -- Jingdong Mall] the home page commodity floor of uni app
- Edge Drawing: A combined real-time edge and segment detector 翻译
- Pytest -- plug-in writing
- Hal library operation STM32 serial port
- go实现命令行的工具cli
- 【小程序项目开发-- 京东商城】uni-app之首页商品楼层
- 线程数据共享和安全 -ThreadLocal
- Keil5中如何做到 0 Error(s), 0 Warning(s).
- 调试定位导航遇到的问题总结
猜你喜欢
随机推荐
【日常训练】1175. 质数排列
C # realize solving the shortest path of unauthorized graph based on breadth first BFS -- complete program display
leetcode 1482 猜猜看啊,这道题目怎么二分?
Mysql知识点
POI导出excel,按照父子节点进行分级显示
Introduction and basic knowledge of machine learning
[reading notes] copywriting realization -- four golden steps for writing effective copywriting
How to use hybrid format to output ISO files? isohybrid:command not found
[small program project development -- Jingdong Mall] the home page commodity floor of uni app
【读书笔记】《文案变现》——写出有效文案的四个黄金步骤
多元线性回归
[machine learning] vectorized computing -- a must on the way of machine learning
Error accessing URL 404
The shell script uses two bars to receive external parameters
Ridge regression and lasso regression
[applet project development -- Jingdong Mall] user defined search component of uni app (Part 1)
【小程序项目开发-- 京东商城】uni-app之分类导航区域
File upload and download
调试定位导航遇到的问题总结
JUC learning




![Servlet [first introduction]](/img/2a/aff3b93e43550d30a33c1683210d3a.png)




