当前位置:网站首页>实现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 操作即可。
边栏推荐
- 第03章_用戶與權限管理
- md5sum操作
- File upload and download
- Cloud native annual technology inventory is released! Ride the wind and waves at the right time
- Install vcenter6.7 [vcsa6.7 (vCenter server appliance 6.7)]
- Include() of array
- Basic concept and classification of sorting
- C语言多线程编程入门学习笔记
- Finally in promise
- mybati sql 语句打印
猜你喜欢
随机推荐
实战 ELK 优雅管理服务器日志
服务器渲染技术jsp
Golang多图生成gif
最好用的信任关系自动化脚本(shell)
安装VCenter6.7【VCSA6.7(vCenter Server Appliance 6.7) 】
Multithreaded printing
xxl-job使用指南
Servlet [first introduction]
The best learning method in the world: Feynman learning method
C language EXECL function
Detailed list of errors related to twincat3 ads of Beifu
HTB-Lame
Redis高效点赞与取消功能
Kmeans
About the application of MySQL
C#实现基于广度优先BFS求解无权图最短路径----完整程序展示
leetcode 1482 猜猜看啊,这道题目怎么二分?
Latest interface automation interview questions
Basic concept and classification of sorting
[linear DP] longest common subsequence









