剑指offer算法题
数学 快速幂运算
题目描述
给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。
保证base和exponent不同时为0
题目分析
首先,本题考察指数的正负、底数是否为零等情况划分。其次,使用快速幂运算得到结果。
快速幂运算介绍:
例如:x22 = x16 * x4 * x2
对于指数22而言
22的二进制为10110,可以发现一个规律,从右到左为01101,对应到指数得到:
x(20* 0) +(21* 1)+(22* 1)+ (23 * 0)+ (24 * 1)
= x16* x4 * x2=x22
下面函数是求ab
public static long pow(long a, long b) {
long result = 1;
long base = a;
while(b > 0) {
if((b & 1) != 0) { // 如果当前二进制尾数为1,将倍数记录
result *= base;
}
base *= base; // 翻倍
b >>= 1; // 二进制数右移
}
return result;
}
下面为此题的Java代码实现
public double Power(double base, int exponent) {
//return Math.pow(base,exponent);
double res = 1 , curr = base;
int n = exponent;
if(exponent < 0){
if(base == 0){
//throw new RuntimeException("分母不能为0!");
}
n = -exponent;
}else if (exponent == 0 ){
return 1;// 0的0次方
}
//快速幂运算
while ( n != 0 ){
if((n & 1) == 1){
res *= curr;// 如果当前二进制尾数为1,将倍数记录
}
curr *= curr;// 翻倍
n >>=1;// 右移一位
}
return exponent >= 0 ?res:(1/res);
}
附 ?:用法
return data != null ? data.getName() : null;
可以把 !=后面代码分为A、B、C三部分
A为布尔表达式(真/假),B 和C为执行语句。
最直观的 A ? B:C ,意思就是如果A为真执行B,否则执行C
上面的代码意思即为如果data不为空,返回data.getName(),如果data为空,则返回null。
参考https://blog.csdn.net/c_yejiajun/article/details/88103036
https://www.nowcoder.com/practice/1a834e5e3e1a4b7ba251417554e07c00?tpId=13&&tqId=11165&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking