当前位置:网站首页>剑指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;
}
香帐簇成排窈窕,金针穿罢拜婵娟。
—— 唐·罗隐
边栏推荐
猜你喜欢
随机推荐
Altium Designer 19.1.18 - draw polygons copper hollow out, for the cursor just capture solutions
docker 搭建mysql 主从复制
中大型商业银行堡垒机升级改造方案!必看!
[Linear Algebra 02] 2 interpretations of AX=b and 5 perspectives of matrix multiplication
Ramnit感染型病毒分析与处置
LeetCode 199: 二叉树的右视图
Redis理解
How to solve the problem that the alarm information cannot be transmitted after EasyGBS is connected to the latest version of Hikvision camera?
com.jacob.com.ComFailException: Invoke of: ActiveDocument
关于std::vector<std::string>的操作
Rt-thread [三] link.lds链接脚本详解
力扣24-两两交换链表中的节点——链表
VSCode—常用快捷键(持续记录
Analysis and treatment of Ramnit infectious virus
UDP通信
Cocoa Application-基础
Ts——项目实战应用enum枚举
一招包治pycharm DEBUG报错 UnicodeDecodeError: ‘utf-8‘ codec can‘t decode
Operations on std::vector
1、网页结构