本文主要是介绍剑指offer__04__数值的整数次方,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目
给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。不考虑大数问题
需要注意的地方
- 基数为 0 ,指数为负的情况
- 优化计算的次数,利用指数相乘的性质
- 判断奇偶性使用位运算,节约计算量
代码
public class Solution {public double Power(double base, int exponent) {if ( exponent == 0)return 1.0;if (base == 0)return 0.0;boolean flag = true;double result = 1.0;if (exponent < 0) {exponent = 0 - exponent;flag = false;result = powerWithUnsignedExponenrt(base, exponent);} else {result = powerWithUnsignedExponenrt(base, exponent);}return flag == true ? result : 1/result;}public double powerWithUnsignedExponenrt(double base, int exponent) {if (exponent == 0)return 1.0;if (exponent == 1)return base;double result = powerWithUnsignedExponenrt(base, exponent >> 1);result *= result;if ((exponent & 0x1) == 1) {result *= base;}return result;}
}
这篇关于剑指offer__04__数值的整数次方的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!