当前位置:网站首页>实现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 操作即可。
边栏推荐
- [reading notes] copywriting realization -- four golden steps for writing effective copywriting
- Go tool cli for command line implementation
- Introduction to EtherCAT
- VMware vSphere 6.7 virtualization cloud management 12. Vcsa6.7 update vCenter server license
- The best learning method in the world: Feynman learning method
- Redis分布式锁的8大坑
- Introduction to webrtc concept -- an article on understanding source, track, sink and mediastream
- C # realize solving the shortest path of unauthorized graph based on breadth first BFS -- complete program display
- 家居网购项目
- Data exchange JSON
猜你喜欢

The best learning method in the world: Feynman learning method

岭回归和lasso回归

C # realize solving the shortest path of unauthorized graph based on breadth first BFS -- complete program display
性能测试常见面试题

雪崩问题以及sentinel的使用

Best used trust automation script (shell)

【小程序项目开发-- 京东商城】uni-app之首页商品楼层

HTB-Lame

Data exchange JSON
![[us match preparation] complete introduction to word editing formula](/img/e4/5ef19d52cc4ece518e79bf10667ef4.jpg)
[us match preparation] complete introduction to word editing formula
随机推荐
Leetcode 1482 guess, how about this question?
JUC learning
JS to find duplicate elements in two arrays
Chapitre 03 Bar _ Gestion des utilisateurs et des droits
[applet project development -- Jingdong Mall] user defined search component of uni app (Part 1)
[linear DP] shortest editing distance
Redis分布式锁的8大坑
咱就是说 随便整几千个表情包为我所用一下
Feign远程调用和Getaway网关
Overview of EtherCAT principle
The value of the second servo encoder is linked to the NC virtual axis of Beifu PLC for display
PHP batch Excel to word
multiple linear regression
EDLines: A real-time line segment detector with a false detection control翻译
第03章_用戶與權限管理
别再说不会解决 “跨域“ 问题啦
Redis tutorial
实战 ELK 优雅管理服务器日志
Kmeans
How to determine the progress bar loaded in the loading interface when opening the game