当前位置:网站首页>实现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 操作即可。
边栏推荐
- Mybati SQL statement printing
- pytest-fixture
- Design of serial port receiving data scheme
- XXL job User Guide
- Go tool cli for command line implementation
- Detailed list of errors related to twincat3 ads of Beifu
- Promise中finally的用法
- So easy 将程序部署到服务器
- 打包iso文件的话,怎样使用hybrid格式输出?isohybrid:command not found
- JS日常开发小技巧(持续更新)
猜你喜欢

Chapitre 03 Bar _ Gestion des utilisateurs et des droits

xxl-job使用指南
![[exsi] transfer files between hosts](/img/c3/128b72aca6e030b2d4be2b6bddbc43.png)
[exsi] transfer files between hosts

Example of Huawei operator level router configuration | example of configuring optionc mode cross domain LDP VPLS

The value of the second servo encoder is linked to the NC virtual axis of Beifu PLC for display

【小程序项目开发-- 京东商城】uni-app之分类导航区域
![[applet project development -- Jingdong Mall] classified navigation area of uni app](/img/cb/b0b79444dc90980cd2220ff9e68549.png)
[applet project development -- Jingdong Mall] classified navigation area of uni app

How the network is connected: Chapter 2 (Part 2) packet receiving and sending operations between IP and Ethernet

C#实现图的深度优先遍历--非递归代码

数据交换 JSON
随机推荐
过滤器 Filter
[us match preparation] complete introduction to word editing formula
监听器 Listener
C#实现基于广度优先BFS求解无权图最短路径----完整程序展示
数据交换 JSON
家居网购项目
[reading notes] copywriting realization -- four golden steps for writing effective copywriting
Promise中finally的用法
调试定位导航遇到的问题总结
安装VCenter6.7【VCSA6.7(vCenter Server Appliance 6.7) 】
xxl-job使用指南
最新接口自动化面试题
Cloud native annual technology inventory is released! Ride the wind and waves at the right time
彻底解决Lost connection to MySQL server at ‘reading initial communication packet
Introduction to the core functions of webrtc -- an article to understand peerconnectionfactoryinterface rtcconfiguration peerconnectioninterface
Introduction to ieda right click source file menu
Analyze datahub, a new generation metadata platform of 4.7K star
Finally in promise
VMware vSphere 6.7虚拟化云管理之12、VCSA6.7更新vCenter Server许可
[exsi] transfer files between hosts