当前位置:网站首页>实现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 操作即可。
边栏推荐
- CX5120控制汇川IS620N伺服报错E15解决方案
- Druid监控统计数据源
- VMware vSphere 6.7虚拟化云管理之12、VCSA6.7更新vCenter Server许可
- Mysql知识点
- Redis 教程
- So easy deploy program to server
- Analyze datahub, a new generation metadata platform of 4.7K star
- How to determine the progress bar loaded in the loading interface when opening the game
- Introduction to EtherCAT
- 手把手带你了解一块电路板,从设计到制作(干货)
猜你喜欢

Druid monitoring statistics source
性能测试常见面试题
![[applet project development -- JD mall] uni app commodity classification page (Part 2)](/img/f3/752f41f5b5cc16c8a71498ea9cabb5.png)
[applet project development -- JD mall] uni app commodity classification page (Part 2)

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

岭回归和lasso回归

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

线程数据共享和安全 -ThreadLocal

最新接口自动化面试题

C语言多线程编程入门学习笔记

Introduction and installation of Solr
随机推荐
Metadata in NFT
go实现命令行的工具cli
[exsi] transfer files between hosts
Leetcode 1818 absolute value, sorting, dichotomy, maximum value
一文讲解发布者订阅者模式与观察者模式
Introduction and basic knowledge of machine learning
EDLines: A real-time line segment detector with a false detection control翻译
[small program project development -- Jingdong Mall] the home page commodity floor of uni app
How to achieve 0 error (s) and 0 warning (s) in keil5
How to use hybrid format to output ISO files? isohybrid:command not found
The value of the second servo encoder is linked to the NC virtual axis of Beifu PLC for display
leetcode 1818 绝对值,排序,二分法,最大值
雪崩问题以及sentinel的使用
咱就是说 随便整几千个表情包为我所用一下
终极套娃 2.0 | 云原生交付的封装
leetcode 1482 猜猜看啊,这道题目怎么二分?
Pytest -- plug-in writing
CX5120控制汇川IS620N伺服报错E15解决方案
Chapitre 03 Bar _ Gestion des utilisateurs et des droits
multiple linear regression