当前位置:网站首页>剑指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;
}
香帐簇成排窈窕,金针穿罢拜婵娟。
—— 唐·罗隐
边栏推荐
- 湖仓一体电商项目(五):内网穿透工具-网云穿
- VSCode - common shortcut keys (continuous recording
- PMP证书在哪些行业有用?
- 【2020】【Paper Notes】Metasurfaces: Multifunctional and Programmable——
- Use ngrok to optimize web pages on raspberry pi (1)
- How to make a video gif?Try this video making gif artifact
- Altium Designer 19.1.18 - 画多边形铜皮挖空时,针对光标胡乱捕获的解决方法
- input事件中文触发多次问题研究php DEBUG
- 【2020】【论文笔记】超表面:多功能和可编程——
- 【论文笔记KDD2021】MixGCF: An Improved Training Method for Graph Neural Network-based Recommender Systems
猜你喜欢

rk3399-9.0 first-level and second-level dormancy
软件测试外包公司怎么样?有什么好处和坏处?为什么没人去?

Driving point cloud format changes bring efficiency improvement

测试薪资这么高?刚毕业20K,仅需3.5个月

PowerBI真经连续剧

Cocoa Application-test

Open source summer | Cloud server ECS installs Mysql, JDK, RocketMQ

力扣24-两两交换链表中的节点——链表

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

重新配置chrome中ffmpeg插件
随机推荐
深度学习 RNN架构解析
EasyGBS接入最新版海康摄像头后无法传递告警信息该如何解决?
MySQL查询为啥慢了?
快速web开发框架——learun framework
Domestic PMP certificate of gold content how
OC-归档(序列化)(了解的不多 没细看)
CPU、内存、显卡等硬件因素也影响着你的深度学习模型性能
力扣19-删除链表的倒数第 N 个结点——链表
Redis理解
论文解读(PPNP)《Predict then Propagate: Graph Neural Networks meet Personalized PageRank》
openresty lua-resty-template页面静态化
Driving point cloud format changes bring efficiency improvement
智能盘点钢筋数量AI识别
2022强网杯web(部分)
ANT1.7下载以及配置方法
Rt-thread [三] link.lds链接脚本详解
webmine网页挖矿木马分析与处置
LeetCode 199: 二叉树的右视图
Autowired autowiring
【线性代数03】消元法展示以及AX=b的4种解情况