当前位置:网站首页>剑指Offer | 数值的整数次方
剑指Offer | 数值的整数次方
2022-08-04 22:12:00 【小雅痞】
实现函数 double Power(double base, int exponent),求base的exponent次方。
1.基础方法
public double Power(double base, int exponent) {
if(exponent == 0){
return 1;
}
if(base == 0){
return 0;
}
if(exponent < 0){
base = 1/base;
exponent = -exponent;
}
double res = 1;
while (exponent>0){
exponent --;
res = res * base;
}
return res;
}
2.使用快速幂
通过使底数平方的方式减少循环次数。例如求38变为(32)4
分为三种情况:
exponent 偶数: xn/2 * xn/2
exponent 奇数: x * xn-1
exponent 0: 返回1
public double Power(double base, int exponent) {
if(exponent == 0){
return 1;
}
if(base == 0){
return 0;
}
if(exponent < 0){
base = 1/base;
exponent = -exponent;
}
return quickPower(base,exponent);
}
private double quickPower(double x,int y){
double res = 1;
while (y!=0){
if((y & 1)!=0) {
//奇数
res = res * x;
}
x = x*x;
y = y >>1;
}
return x;
}
香帐簇成排窈窕,金针穿罢拜婵娟。
—— 唐·罗隐
边栏推荐
- Leaflets of three bouquet of roses
- 《剑指offer》刷题分类
- 【论文笔记KDD2021】MixGCF: An Improved Training Method for Graph Neural Network-based Recommender Systems
- [Linear Algebra 02] 2 interpretations of AX=b and 5 perspectives of matrix multiplication
- Altium Designer 19.1.18 - 保护锁定的对象
- 阿里巴巴2022届秋招面试真题和答案!
- 视频gif如何制作?试试这个视频制作gif神器
- rk3399-9.0一级二级休眠
- 后排乘客不系安全带?事故瞬间被甩出
- Hardware factors such as CPU, memory, and graphics card also affect the performance of your deep learning model
猜你喜欢

七夕,当爱神丘比特遇上牛郎和织女

promise详解

三个多月、40余场面试浓缩为6000字

【组成原理 六 存储器类型】

【论文笔记KDD2021】MixGCF: An Improved Training Method for Graph Neural Network-based Recommender Systems

1319_STM32F103串口BootLoader移植

【Social Marketing】WhatsApp Business API: Everything You Need to Know

使用cpolar优化树莓派上的网页(2)

Ts——项目实战应用enum枚举

【TCP/IP 四 IP 网际协议】
随机推荐
Oracle增加表空间解决ORACLE ORA-01653: unable to extend table报错
As hot as ever, reborn | ISC2022 HackingClub White Hat Summit was successfully held!
Altium Designer 19.1.18 - draw polygons copper hollow out, for the cursor just capture solutions
论文解读(PPNP)《Predict then Propagate: Graph Neural Networks meet Personalized PageRank》
Flutter 实现背景图片毛玻璃效果
ES6高级-Promise的用法
【Social Marketing】WhatsApp Business API: Everything You Need to Know
OC-拷贝
The Record of Reminding myself
Driving point cloud format changes bring efficiency improvement
Hardware factors such as CPU, memory, and graphics card also affect the performance of your deep learning model
How to right use of WebSocket in project
docker 部署redis集群
docker 搭建mysql 主从复制
基于事实的结果
视频gif如何制作?试试这个视频制作gif神器
深度学习 RNN架构解析
Develop your own text recognition application with Tesseract
synchronized和ReentrantLock都很丝滑,因为他们都是可重入锁,一个线程多次拿锁也不会死锁,我们需要可重入
input事件中文触发多次问题研究php DEBUG