当前位置:网站首页>实现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 操作即可。
边栏推荐
- Clion and C language
- 家居网购项目
- ES6解构语法详解
- [linear DP] shortest editing distance
- E15 solution for cx5120 controlling Huichuan is620n servo error
- Depth first traversal of C implementation Diagram -- non recursive code
- 终极套娃 2.0 | 云原生交付的封装
- How to verify whether the contents of two files are the same
- 限流组件设计实战
- Stop saying that you can't solve the "cross domain" problem
猜你喜欢
随机推荐
Chapter 03_ User and authority management
Include() of array
VMware vSphere 6.7 virtualization cloud management 12. Vcsa6.7 update vCenter server license
Const and the secret of pointers
split(),splice(),slice()傻傻分不清楚?
EtherCAT简介
Data exchange JSON
【读书笔记】《文案变现》——写出有效文案的四个黄金步骤
[QT] add knowledge supplement of third-party database
Hello World generation
Install vcenter6.7 [vcsa6.7 (vCenter server appliance 6.7)]
手把手带你了解一块电路板,从设计到制作(干货)
Chapitre 03 Bar _ Gestion des utilisateurs et des droits
C语言多线程编程入门学习笔记
Is it safe to open an account online in a small securities firm? Will my money be unsafe?
gcc使用、Makefile总结
Redis 教程
The shell script uses two bars to receive external parameters
CX5120控制汇川IS620N伺服报错E15解决方案
[applet project development -- Jingdong Mall] classified navigation area of uni app









