当前位置:网站首页>实现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 操作即可。
边栏推荐
猜你喜欢
实战 ELK 优雅管理服务器日志
[small program project development -- Jingdong Mall] the home page commodity floor of uni app
Common interview questions for performance test
C # realize solving the shortest path of unauthorized graph based on breadth first BFS -- complete program display
Redis分布式锁的8大坑
线程数据共享和安全 -ThreadLocal
EDLines: A real-time line segment detector with a false detection control翻译
【小程序项目开发-- 京东商城】uni-app之首页商品楼层
Druid监控统计数据源
POI exports excel and displays hierarchically according to parent-child nodes
随机推荐
E15 solution for cx5120 controlling Huichuan is620n servo error
md5sum操作
Redis分布式锁的8大坑
Feign远程调用和Getaway网关
C language EXECL function
Clion and C language
Mybati SQL statement printing
Summary of problems encountered in debugging positioning and navigation
ctfshow爆破wp
Force buckle - sum of two numbers
Mysql知识点
8 pits of redis distributed lock
ES6解构语法详解
An article explaining the publisher subscriber model and the observer model
PHP batch Excel to word
ECMAScript 6.0
Elk elegant management server log
pytest-fixture
打包iso文件的话,怎样使用hybrid格式输出?isohybrid:command not found
Chapitre 03 Bar _ Gestion des utilisateurs et des droits